MATLAB: For loop does not work properly

for loop

I have the following code:
for
.
.
. Some conditions here
.
.
if (i >= 2)
i
for u=1:size(cent,1)
a(u,:) = sqrt((S(i,1)-cent(u,1))^2 + (S(i,2)-cent(u,2))^2 + (S(i,3)-cent(u,3))^2)
stor = size(cent,1)
if a <= 2*r/1000;
continue;
elseif stor >= e
break;
else
con = size(cent,1) + 1
cent(con,:) = S(i,:)
end
end
end
end
cent
So what I want the for loop to add S(i,:) as a matrix row if it satisfies the if condition, and if the numbers of rows does not exceed e. If it does not match the a condition, I want it to go back to the first for loop, and then recalculate S.
The output I get, shows that it works almost fine, but duplicates some rows. Why?
Output:
i =
2
a =
0.4423
stor =
1
con =
2
cent =
0.7738 0.8484 0.9085
0.8241 0.4105 0.8714
i =
3
a =
0.6804
stor =
2
con =
3
cent =
0.7738 0.8484 0.9085
0.8241 0.4105 0.8714
0.1843 0.8812 0.5704
a =
0.6804
0.8493
stor =
3
con =
4
cent =
0.7738 0.8484 0.9085
0.8241 0.4105 0.8714
0.1843 0.8812 0.5704
0.1843 0.8812 0.5704
i =
4
a =
0.7034
stor =
4
con =
5
cent =
0.7738 0.8484 0.9085
0.8241 0.4105 0.8714
0.1843 0.8812 0.5704
0.1843 0.8812 0.5704
0.6145 0.3154 0.4782

Best Answer

if a <= 2*r/1000;
means the same thing as
if all(all(a <= 2*r/1000))
which is to say it is only considered true if all of the values in a satisfy the comparison. If even one of them does not satisfy the comparison, then control will pass on to the elseif branch. If that elseif branch is also not satisfied then the else to it could end up being executed multiple times for the same i value with different u values.