views:

199

answers:

3

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.

+4  A: 

Hi

Tested quickly

mask2+mask1.*(mask2==0)

for your first output, I'll leave you to generalise the solution

Regards

Mark

High Performance Mark
+2  A: 
mask1=[0 5 5;0 5 5];
mask2=[4 4 0;4 4 0];

idx = find(mask2==0);    %# find zero elements in mask2
mask2(idx) = mask1(idx)  %# replace them with corresponding mask1 elmenets

mask3=[0 6 0;0 6 0];
idx = find(mask3==0);    %# find zero elements in mask3
mask3(idx) = mask2(idx)  %# replace them with corresponding mask2 elmenets
Amro
It's much faster to use logical indexing than to use the find function...
Mark E
True. @gnovice added that, I kept it this way as an alternative solution
Amro
+4  A: 

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
gnovice
"%#" is a pragma in Matlab. I get "Unrecognized Compiler pragma" warnings with this.
Andrew Janke
@Andrew: `%` creates a comment, so nothing after it should be evaluated at all. The `#` is just there to make the coloring of the comments on SO look better.
gnovice
@Andrew: I didn't know that.. Apparently there's a few pragmas: http://blogs.mathworks.com/desktop/2008/09/22/matlab-pragmas/
Amro
Interesting... I wasn't aware of pragmas either. I haven't noticed *any* unusual warnings using `%#` in comments in R2009a.
gnovice