Search code examples
matlabmatrixpixel

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.


Solution

  • 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