vectorize a function that calls the itterator (condition in a loop)
Show older comments
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!
Accepted Answer
More Answers (1)
Guillaume
on 14 Feb 2018
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
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!