0
votes

Say you have two matrices as follows:

A = [1 0.2 1; 0.4 0.4 1; 1 0.6 1; 0.9 0.7 1];

B = [33 75 250; 6 34 98; 55 3 4; 153 66 30];

Say we want to create a new matrix C that contains the values of B where A=1.

I think in matlab we can do the following for this:

C = B(A==1);

But, how can I fill the other cells with the original values of A, as I think in our case, we will just get a vector with the B elements which their corresponding value in A=1? And, I want C to have the same dimensions of B but with the original values of A that are not equal to 1 instead of having 0 values.

2
There is something wrong with your question as you are asking to assign some values of B to C and then all other values should be those of B, which means that in the end C will be identical to B. - s.bandara
Yes, I understood that too, but I think he is talking about keeping the dimensions, and filling the other values with zeros. - mmumboss
Sorry, I have edited my question. I meant the original values of A not B. Is my question more clear now? Thanks - Simplicity

2 Answers

1
votes

Yes, you can do it like this:

C= A.*(A~=1)+B.*(A==1)

Which gives:

C =

33.0000    0.2000  250.0000
0.4000    0.4000   98.0000
55.0000    0.6000    4.0000
0.9000    0.7000   30.0000
0
votes

C will have to be initialized anyways, so let's initialize it to A as in C = A;. Then, MATLAB allows you to index the left-hand side as in C(A==1) = B(A==1); to replace all elements in C by those in B for which A == 1. All other elements will stay the same.