MATLAB: How to vectorize for..loop with nested “if” and “break” statements

for loopiterationloopsMATLABperformancevectorization

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!

Best Answer

Hi, it seems you're trying to do something like
% initialize indices
Rmin = 3;
Rmax = 8;
Cmin = 2;
Cmax = 7;
% initialize a zero matrix with some values to one.
img = zeros(10);
img(4,5) = 1; % inside Rmin/Rmax, Cmin/Cmax

img(3,7) = 1; % inside Rmin/Rmax, Cmin/Cmax
img(3,8) = 1; % OUTSIDE Rmin/Rmax, Cmin/Cmax => won't be in the result
% get all the points equal to 1 in the Rmin/Rmax, Cmin/Cmax submatrix
[allx,ally] = find(img(Rmin:Rmax,Cmin:Cmax)==1);
% correct the indices to fit those in the whole matrix.
allx = allx + Rmin - 1;
ally = ally + Cmin - 1;
% get the first component :
x1 = allx(1);
y1 = ally(1);