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.