MATLAB Answers


Binary mask operation: vector into nonzero part of mask in 1 statement?

Asked by Jurgen
on 11 Dec 2012

I have a logical matrix MASK and a vector VEC with real numbers (uint8 mostly). nnz(MASK) equals length(VEC).

I create a new matrix NEW where the logical 1's in MASK are replaced by the values in VEC--in sequential order:

 NEW(NEW>0) = VEC; 

Can I do this with 1 statement? Because in practice I want to replace NEW with VEC since I dont need VEC anymore after the operation, and don't want to pile up variables. MASK should remain untouched.



1 Answer

Answer by Image Analyst
on 11 Dec 2012

I think you can just do:

VEC(~MASK) = 0;

I think this will do the same thing - set VEC to zero where MASK is false, and VEC stays VEC where MASK is true.

By the way, you can use clear('variableName') to get rid of variables you don't need anymore.


Please give small examples for vec and mask, something like:

mask = false(5,5);
mask(2:4, 2:4) = true
vec = randi(255, [3,3])

and give what you want vec to look like when all is said and done.

It looks like in your code demo that vec will need to get resized, so no, there's no way to do it in a single assignment. Use clear('VEC') to get rid of VEC after you've created NEW.

on 12 Dec 2012

Thanks, in the end I just made a function that takes the mask and vector and spits out a substituted image. If you cant beat em, join em :)

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!