Matlab Class Home      Class Outline      Previous Task      Next Task      Main Class Page      Evaluation 6

Task 6.1 Detail: Using loops to address individual values in arrays

Summary of new tools and commands.

Task: Write a script to calculate the gain from compound annual interest for specified interest rates and investment durations. Create a 2 panel plot showing the principle and interest vs year.

The concept of compound interest is that the interest (or investment return) is added to the principle so that the investment grows faster. For a given principle (P(t)) at time t, the interest (I(t)) will be I(t)=r*P(t), where r is the interest rate, and the new principal is P(t+1)=P(t)+I(t). Time, in this notation, is a year counter and we assume that the interest calculation, for simplicity, is done once per year at the end of the year.

Because the next value of this calculation depends on the current value (a property called recursion), we cannot use the simple vector operations that we have been using so far. Instead we need to calculate the results sequentially, which requires that we set up a loop to step through the calculations.

The MATLAB looping construct (for) uses a loop index which is a counter for the number of times to execute the loop. In the following case, the variable i is the loop index. The looping command is for i=1:10 to indicate the beginning of the block of calculations to be done and end to be the end of the block. Recall that 1:10 is a list that starts at 1, increases by 1, up to the value 10.

  for i=1:10  % i starts at 1 and increments each pass through the loop
%      (do calculations that depend on i)
     disp(['loop index is ' num2str(i)])
  end

The for command specifies a loop index (variable) which changes with each pass through the loop from the start to the end value (from 1 to 10 in steps of 1 in the above example). The loop index changes by 1 for each pass unless otherwise specified. The counter is an integer. It is a dummy variable that is only used to count times through the loop, although it can be used in various ways to have the calculation in the loop change.

By convention, the body of the for loop is indented; that is, has several leading blanks to shift the lines to the right. This clearly marks the lines that are inside the loop. The end statement starts on the same column as the for command it is link to.

To solve the compound interest problem, consider the following commands:

  r= 0.02;   % annual interest rate (2%) as a fraction
  Po = 100;  % initial principle
  Nyear=20;  %  total number of years of investment
  P=zeros(Nyear+1,1);   %  array to hold principle
  I=zeros(Nyear,1);   %  array to hold interest at the end of the year
  P(1)=Po;  % starting principle
  for yr=1:Nyear
    I(yr) = r*P(yr);       % interest at the end of the current year
    P(yr+1) = P(yr)+I(yr); % principle at the beginning of the next year
  end
  disp(['Final Principle: ' num2str(P(Nyear+1))])
Notice that the arrays holding the principle and interest were defined first, then the values were filled in with the loop. Because we use the loop index (yr) to refer to locations in the array, we use integers, starting with 1.

If you want to do this calculation for monthly compound interest, you could keep separate time indexes to keep track of months and years. This means that it is possible to have a loop within a loop, which is called "nested loops".

A flow chart for this monthly interest problem is

%%%  monthly compound interest
%%%  set annual percentage rate, initial principle, and number of years
%%%  calculate the monthly percentage rate
%%%  set up array storage for principle and interest
%%%  set initial values for principle and time counter
%%%  loop over years
%%%     loop over months
%%%       calculate monthly interest, add to principle
%%%  display the final principle

The script for this monthly interest problem is

%%%  monthly compound interest
%%%  set annual percentage rate, initial principle, and number of years
  r= 0.02;   % annual interest rate (2%) as a fraction
  Po = 100;  % initial principle
  Nyear=20;  %  total number of years of investment
%%%  calculate the monthly percentage rate
  mr= r/12;   % monthly interest rate as a fraction
%%%  set up array storage for principle and interest
  P=zeros(Nyear*12+1,1);   %  array to hold principle
  I=zeros(Nyear*12,1);   %  array to hold interest
%%%  set initial values for principle and time counter
  P(1)=Po;
  t=0;  % count the number of months
%%%  loop over years
  for yr=1:Nyear
%%%     loop over months
    for m=1:12   %  loop over months
      t=t+1;  % set a counter for total months
%%%       calculate monthly interest, add to principle
      I(t) = mr*P(t);       % interest for the current month
      P(t+1) = P(t)+I(t); % principle for next month
    end
  end
%%%  display the final principle
  disp(['Final Principle: ' num2str(P(Nyear*12+1))])

There are many uses for this sort of looping construct. Most of the earlier calculations could be done with loops:

  x=0:.1:10;
  nx=length(x);
  y=zeros(size(x));
  for i=1:nx
    y(i)=cos(2*pi*x(i));
  end
These commands are equivalent to x=0:.1:10;y=cos(2*pi*x);. It is much more efficient (executes in a shorter time) to use the one line statement rather than the for loop. Most of the MATLAB scripts that we run are so fast, such efficiency concerns are not relevant. But, you should be aware of this issue.

Flow chart for the task:

%%%  Annual compound interest
%%%  set interest rate, principle and duration
%%%  set up arrays
%%%  loop over years
%%%     calculate interest and principle
%%%  plot interest and new principle

Script to complete task:

%%%  Annual compound interest
%%%  set interest rate, principle and duration
  r= 0.02;   % annual interest rate (2%) as a fraction
  Po = 100;  % initial principle
  Nyear=20;  %  total number of years of investment
%%%  set up arrays
  P=zeros(Nyear+1,1);   %  array to hold principle (needs 1 extra value)
  I=zeros(Nyear,1);   %  array to hold interest at the end of the year
  Y=zeros(Nyear,1);   %  array to hold current year
  P(1)=Po;  % starting principle
%%%  loop over years
  for yr=1:Nyear
    Y(yr)=yr;  %  current year count
%%%     calculate interest and principle
    I(yr) = r*P(yr);       % interest at the end of the current year
    P(yr+1) = P(yr)+I(yr); % principle at beginning the next year
  end
  YP=[Y(:); Nyear+1]; % P is one value longer than Y, so need extended year array
%%%  plot interest and new principle
  figure
  subplot(1,2,1)
   plot(YP,P)
   title('Principle')
   xlabel('year')
  subplot(1,2,2)
   plot(Y,I)
   title('Interest')
   xlabel('year')

Matlab Class Home      Class Outline      Previous Task      Next Task      Main Class Page      Evaluation 6


email: J. Klinck