How do I merge two masks together in MATLAB?
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.
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
Tested quickly
mask2+mask1.*(mask2==0)
for your first output, I'll leave you to generalise the solution
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
If the masks are binary you can just do:
result = mask1;
result(mask2 ~= 0) = true;
% and you can add many masks as you want to the resultant mask.
% result(maskn ~= 0) = true;
If they are not binary @gnovice answer is perfect.
精彩评论