Simplicity
Simplicity

Reputation: 48976

Filling the pixels with values of another matrix

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.

Upvotes: 0

Views: 85

Answers (2)

mmumboss
mmumboss

Reputation: 699

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

Upvotes: 1

s.bandara
s.bandara

Reputation: 5664

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.

Upvotes: 0

Related Questions