How to vectorize for..loop with nested "if" and "break" statements
Show older comments
Dear colleagues, I am trying to vectorize the following for..loop in my matlab code:
for c=Cmin:Cmax % Cmin, Cmax are columns indices
for r=Rmin:Rmax % Rmin, Rmax are rows indices
if(img1(r, c)==1) % img1 is a binary image
x1 = r;
y1 = c;
break;
end
end
end
The problem I am facing is the inner "if" and "statement" to be included in the vectorized code. I have followed several vectorization techniques, but I haven't happened to see one that include nested conditions. Any idea please. Thank you!
4 Comments
dpb
on 2 Mar 2016
'Pends on what needs to be done inside the loop besides what is (presumably) demo code rather than real as the end result of the above snippet will simply be the last set that meet the criterion; all the earlier are lost/overwritten. Is saving an array of those locations sufficient for use later or is something else needing done at the time of the discovery???
Jos (10584)
on 2 Mar 2016
it is the first occurrence , due to the break statement
Kevin Claytor
on 2 Mar 2016
Are you actually trying to determine if this is a binary image? Because there are better ways of doing that, and your code snippet above would risk misclassifying any integer-valued image as a binary image.
"_it is the first occurrence , due to the break statement"_
The break only terminates the inner loop; it'll then go on and start over the outer loop. Since x1, y1 are each a single variable, you'll overwrite the first column location with the second, then the third, leaving at the end only the last column first row as the one and only pair of values retained.
Accepted Answer
More Answers (1)
Jos (10584)
on 2 Mar 2016
[x1,y1] = find(img1(Rmin:Rmax,Cmin:Cmax)==1,1,'first')
and perhaps correct for the offset
x1 = x1 + Rmin - 1 ...
2 Comments
Baraka Maiseli
on 3 Mar 2016
Edited: Baraka Maiseli
on 3 Mar 2016
Baraka Maiseli
on 3 Mar 2016
Categories
Find more on Object Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!