Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How to exit a for loop

  1. Nov 24, 2011 #1
    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!
     
  2. jcsd
  3. Nov 24, 2011 #2

    Mark44

    Staff: Mentor

    From the Getting Started documentation for Matlab:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook