Search code examples
matlabindices

Passing certain values of a matrix usi a logical mask


Assum I have a matrix of logicals MxN:

mask=[0 0 0 0 0;
     0 1 1 0 0;
     0 1 1 0 0;
     0 0 0 0 0;
     0 0 0 0 0];

in this case M=N=5. A second matrix A with the sizes 'MxNx3' (RGB image). I want to pass a function values of A with respect to the mask. For example all values that are not part of the mask:

   foo(A(~mask));  

Sure this line of code is useless since mask gives me indices of only one of the RGB colors.

  • what is the correct way to do this?
  • Can I get away with a one line?

Solution

  • You can use repmat to repeat your mask 3 times in the third dimension. This will create a nnz(~mask) * 3 element vector. You can reshape the result of the repmat operation such that the rows are the true elements in your mask and the columns are the third dimension

    foo(reshape(A(~repmat(mask, [1 1 3])), [], 3))
    

    You could also do something like this answer to accomplish something similar.