Loops

A Matlab script is a file that contains instructions to the matlab interpreter, with one instruction per line, that are read one at a time from the top of the script to the bottom. You can, however, divert this flow using a for loop, which allow you to execute a block of code many times. Open a new Matlab script loop.m and write the code like this format;

for loop_index = vector
          code;
      end

For example;

for i = 1:5
          six_times_i = 6 * i
      end

What do you think will be displayed to the screen?

Loops are very powerful. It has two parts;

  • Range vector. This is a collection of values that over which the loop will iterate. In this case, this is the numbers 1 to 5 ( the 1 : 5 command returns a collection of values from 1 to 5 ). The loop is executed once for each value in the collection.
  • Body. This is all of the code that is indented. The loop allows the code in the body to be executed multiple times. In this case, the code in the body that displays a line of the six times table is executed five times, once for each value in the range.
a = -10:10;
      for i = 1:length(a)
          a(i)
      end

displays all of the numbers from -10 to 10.

a = 1:20;
      sum_a = 0;
      for i = 1:length(a)
          sum_a =  sum_a + a(i)
      end
      disp(sum_a)

goes through every element in a and add it to the total sum. At the end, we can display a sum of a.

a = 1:20;
      ind = [1 10 14 13];
      sum_a = 0;
      for i = ind
          sum_a =  sum_a + a(i)
      end
      disp(sum_a)

adds up just the elements indexed by the numbers in the ind vector.

a = 1:20;
      sum_vec = zeros(1, length(a));
      sum_a = 0;
      for i = 1 : length(a)
          sum_a =  sum_a + a(i);
          sum_vec(i) = sum_a;
      end
      figure;plot(sum_vec)

adds up just the elements indexed by the numbers in the ind vector and stores the cumulative sum of a in anbother vector. Diplays a figure showing the cumulative sum.

Note as well in the last example that you can nest loops (one loop can be inside another), but you must be careful within indentation to ensure that a line of code is in the loop you want. Try writing this;

for i = 1 : 10
          for j = 1 : 10
              i_times_j = i * j
          end
      end

This above code is indented only into the first loop for i = 1 : 10, and is not part of the second loop for j = 1 : 10 as is required for this example.



Previous | Up | Next