R – How to merge two masks together in MATLAB

maskmatlabmatrixmerge

I have two masks that I would like to merge together, overwriting mask1 with mask2 unless mask2 has a zero. The masks are not binary, they are some value that is user defined in the region of interest and 0 elsewhere.

For example if:

mask1=[0 5 5;0 5 5];
mask2=[4 4 0;4 4 0];

then I would want an output of [4 4 5;4 4 5]. And if I then had another mask,

mask3=[0 6 0;0 6 0];  

then I would want an output of [4 6 5;4 6 5]

There has got to be an easy way of doing this without going through and comparing each element in the matrices. Timing is important since the matrices are quite large and I need to merge a lot of them. Any help would be great.

Best Solution

Another option is to use logical indexing:

%# Define masks:

mask1 = [0 5 5; 0 5 5];
mask2 = [4 4 0; 4 4 0];
mask3 = [0 6 0; 0 6 0];

%# Merge masks:

newMask = mask1;                %# Start with mask1
index = (mask2 ~= 0);           %# Logical index: ones where mask2 is nonzero
newMask(index) = mask2(index);  %# Overwrite with nonzero values of mask2
index = (mask3 ~= 0);           %# Logical index: ones where mask3 is nonzero
newMask(index) = mask3(index);  %# Overwrite with nonzero values of mask3