There are two main problems with the loops you have set up: you run the risk of not defining your variables (which is causing your errors) and they are very inefficient.
Replace this
t=0;
for u=1:ri
for v=ch:-1:1
if B(u,v)
t=t+1;
Y1=u+r1;
X1=v;
break
end
end
end
t=0;
for u=1:ri
for v=ch:c
if B(u,v)
t=t+1;
Y2=u+r1;
X2=v;
break
end
end
end
with this
[u,v]=deal(1:r1,ch:-1:1);
[u_ind,v_ind]=find(B(u,v))
if ~isempty(u_ind)
[u_ind,v_ind]=deal(u_ind(end),v_ind(end));
Y1=u(u_ind)+r1;
X1=v(v_ind);
else
Y1=0;X1=0;
end
[u,v]=deal(1:r1,ch:c);
[u_ind,v_ind]=find(B(u,v))
if ~isempty(u_ind)
[u_ind,v_ind]=deal(u_ind(end),v_ind(end));
Y2=u(u_ind)+r1;
X2=v(v_ind);
else
Y2=0;X2=0;
end
Best Answer