2
votes

I am new in MATLAB programming and unable to solve the following problem

I have a matrix A of size example: 1*16 such as

A = [.01 0 0 0 .42 0 0 0 .13 0 0 0 .09 0 0 .32]

and another matrix B of size 16*16 with all values of column the same

B = [.12 .18 .08 .17 .43 .13 .13 .24 .09 .11 .04 .08 .10 .15 .08 .43]

each row same as first row.

I want to replace columns of B with columns of A but if 0 is present in A I should keep the value of B of that column the same.

I want to get output as 16*16 matrix with a sample row matrix C as:

C = [.01 .18 .08 .17 .42 .13 .13 .24 .13 .11 .04 .08 .09 .15 .08 .32]

I would be pleased to get support.

3
@Mikhail_Sam, when editing, please use line codes instead of backtick code for separate lines of code by indenting 4 spaces as opposed to putting things in backticks.Adriaan
@Adriaan ah okey! what'is why you reject my first editing? But why it is better? Are some differences between this two methods?Mikhail_Sam
Your edit was approved, no worries. I just did some more editing afterwards. the backticks are used for inline code formatting, e.g. like in excaza's post. The code block at the top of his post though, needs to be indented, to prevent white lines between the lines.Adriaan

3 Answers

2
votes

you can go this way:

k = find(A);
C = B(1,:);
C(k) = A(k);
B = repmat( C,16,1);

It's not so elegant like another answers, but it's only shows how to do it for 16x16 matrix B not 1x16.

2
votes

You can accomplish this using logical indexing:

A = [.01 0 0 0 .42 0 0 0 .13 0 0 0 .09 0 0 .32];
B = [.12 .18 .08 .17 .43 .13 .13 .24 .09 .11 .04 .08 .10 .15 .08 .43];

C = A; % Use A as a starting point
C(A==0) = B(A==0);
C = repmat(C, 16, 1);

To break this down a bit, the logical equal (==) when applied to an array returns an array of the same size that is true where the condition is satisfied and false when it is not. If you index an array of the same size as your logical array, the return is the values of your array where the logical array is true.

For example, if we do:

myarray = [1 2 3 4];
test = myarray < 3;

We get the following return:

test =

     1     1     0     0

Now if we index myarray with test:

newarray = myarray(test);

We obtain:

newarray =

     1     2

To go one step further, we can do something like the following to align with the above solution:

newarray = zeros(size(myarray));
newarray(test) = myarray(test);

Which returns:

newarray =

     1     2     0     0
1
votes
C=B;
C(A~=0) = A(A~=0)

C =

    0.0100    0.1800    0.0800    0.1700    0.4200    0.1300    0.1300    0.2400    0.1300    0.1100    0.0400    0.0800    0.0900    0.1500    0.0800    0.3200

Using logical indexing, of course.

To get the full matrix of equal rows, use repmat:

C = repmat( C,16,1);

But if you want to access values only, you'd better stick with the vector form, since that uses less memory.