Search code examples
matlabmatrixmatrix-indexing

How to use logical values and select data in another matrix?


I am getting frustrated with MATLAB when I tried to get the data back in matrix format. But every time i only get back the answer in a single column format. I will illustrate my question:

For example,

A = [1 -3 2;5 4 7;-8 1 3];

L = logical(mod(A,2))

L =

     1     1     0
     1     0     1
     0     1     1

now I have another set of matrix sample called B, C is the output I would like to see

B = [100 300 200;500 400 700;800 100 300];

C = B(L)

C =

     100
     500
     300
     100
     700
     300

I don't want it to remain as a single column. I wonder what I can do to make C returned to me in this matrix format?

C =

     100     300     0
     500     0       700
     0       100     300

Thanks a lot, guys!!!


Solution

  • Logical indexing will select only the elements from the matrix for which the logical matrix is true. Obviously this means it can't retain it's original shape, since the number of elements will change. There are a few ways of doing what you want to do; the most efficient is probably:

    C = B;
    C(~L) = 0;
    

    This sets C to B, then sets every element of the matrix for which L is false to zero.