Matlab - For Loop                                                      Home : www.sharetechnote.com

 

 

 

Format

 

 

< Case 1 >

    For var = startVal:endVal

         body; // do what you need to do

    end;

 

< Case 2>

    For var = startVal:step:endVal

         body; // do what you need to do

    end;

 

< Case 3>

    For var = vector

         body; // do what you need to do

    end;

 

 

 

Examples

 

 

Ex 1 >

    s = 0;

    for i = 1:10

      s = s + i;

    end;

     

    s

Output

    s =

     

        55

 

 

Ex 2 >

    s = 0;

    for i = 1:0.1:10

      s = s + i;

    end;

     

    s

Output

    s =

     

        500.5000

 

 

Ex 3 >

    s = 0;

    for i = [1 3 5 9 20]

      s = s + i;

    end;

     

    s

Output

    s =

     

        38