vectorize a function that calls the itterator (condition in a loop)

Hello, I am trying to go through a matrix (x,y) and at each point of the matrix, if the number is in-between a certain number, add a 1 to the same zero matrix, else put a zero.
Here is my code in classical object programming:
if true
sz = size(img);
A = zeros(sz(1),sz(2));
for i = 1:sz(1)
for j = 1:sz(2)
if (img(i,j) < minthreshold)||((img(i,j) > maxthreshold)))
A(i,j) = 0;
else
A(i,j) = 1;
end
end
end
I know how to go through a matrix with the vectored syntax, but I wouldn't know when that condition is respected, I want to reference the (i,j) where the matrix, at the time, iterating. I thought the loop could be replaced by:
if true
if (img(1:1:sz(1),1:1:sz(2)) < minthreshold)||((img(1:1:sz(1),1:1:sz(2)) > maxthreshold))
A() = 0;
else
A = 1;
end
end
But when the condition is True, I don't know how to adress my matrix A() at the same location that the matrix img is at to put a value of 1 or 0.
Thank you!

 Respuesta aceptada

Stephen23
Stephen23 el 14 de Feb. de 2018
Editada: Stephen23 el 14 de Feb. de 2018
Simplest:
A = img>=minthreshold & img<=maxthreshold
If you really wanted to, you could use indexing:
A = zeros(sz);
A(img>=minthreshold & img<=maxthreshold) = 1

Más respuestas (1)

You don't use any if for that. You get the result as a logical array and use that logical array as a mask:
A = ones(size(img), 'like', img);
isinrange= img < minthreshold | img > maxthreshold; %note that you CANNOT use || here
A(isinrange) = 0;
However, since you're only putting 0 and 1 in your output, this can be simplfied even further to:
A = ~(img < minthreshold | img > maxthreshold);
%or
A = img >= minthreshold & img <= maxthreshold;
Finally, note that
x(1:1:sz)
is exactly the same as
x(1:end)
and even simpler
x
as I have done above

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by