5.3 For Loops

A for loop is a construction of the form

for i=1:n, program, end
Here we will repeat program once for each index value i. Below are some sample programs.

function c=add(a,b)

% c=add(a,b). This is the function
% which adds the matrices a and b.
% It duplicates the MATLAB function
% a+b.

[m,n]=size(a);
[k,l]=size(b);
if m~=k | n~=l,
   error('matrices not the same size');
   return,
end
c=zeros(m,n)
for i=1:m,
   for j=1:n,
      c(i,j)=a(i,j)+b(i,j);
   end
end

The next program is matrix multiplication.

function c=mult(a,b)

% c=mult(a,b). This is the matrix product
% of the matrices a and b.
% It duplicates the MATLAB function
% a*b.

[m,n]=size(a);
[k,l]=size(b);
if n~=k,           
   error('matrices are not compatible');
   return,
end
c=zeros(m,l)
for i=1:m,
   for j=1:n,
      for p=1:n,
         c(i,j)=a(i,j)+a(i,p)*b(p,j);
      end
   end
end

Notice how the branch construction was used for error messages.


Next Section: 5.4 While Loops


Created by F.G. Garvan (fgarvan@ufl.edu) on Wed, Oct 01, 97
Last update made Thu Oct 2 11:22:22 EDT 1997.
Back to 5.2 Branching
Back to Table of Contents
EMAIL: fgarvan@ufl.edu fgarvan@ufl.edu