# How to exit a for loop

## Main Question or Discussion Point

Hello everyone!

I just start using C programming as i execute a numerical method in MATlab for a heat diffusion problem. I have solve my problem but my code can be a little better. HERE is part of my code and i use comments to ask for help!

for i=2:10
E(i,1)=20;
T(i,1)=1;
Q(i,1)=0;
end

for t=1:50
for i=1:11
R(i,1)=E(i,1);
end
for m=1:100 %this is the loop i want to exit,it counts iterations%
Sum=0;
for i=2:10
T(i,1)=a*E(i,1)+b*(E(i-1,1)+E(i+1,1)+T(i-1,1)+T(i+1,1)); %9 temperatures i want
end %to calculate%
for i=2:10
Sum=Sum+abs(T(i,1)-Q(i,1)); %this is the error i want to calculate%
end
if Sum<=0.001 % when this is true i want to leave the "m" loop%
m=101; % here is the help that i need,i want to leave the "m" loop%
else %without changing the value of m,in fact i want to know how many%
for i=2:10 %iterations i need until the error is <=0%
Q(i,1)=T(i,1);
end
end

end
for i=2:10
E(i)=T(i);
end
end

i read something about "break" but i m not sure how to use it
Thanks a lot for your time!

Related MATLAB, Maple, Mathematica, LaTeX News on Phys.org
Mark44
Mentor
From the Getting Started documentation for Matlab:
break
The break statement lets you exit early from a for loop or while loop. In
nested loops, break exits from the innermost loop only.
Here is an improvement on the example from the previous section. Why is
this use of break a good idea?
Code:
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x