Q:

Matlab - How to mask a 3-D image using a binary image

I have an image with red, green, blue channel and a binary version of the image.
What I want to do is concatenate those 2 images so that the binary image works as the mask for the normal image.
I want to select only the pixels from the color image which are 1 in binary.
I know that this should work with cat, or even with repmat, but since I'm pretty new to Matlab I can't figure out how to do this, even after reading the docs of the functions.

A:

If you have a 3-D image I and a binary mask M, you can mask the irrelevant bits to zero either by multiplying the image by the mask:
I = bsxfun(@times, I, M);    

or by logical indexing:
I(~mask(:, :, ones(1, size(I, 3)))) = 0;

