Chapter 2. Programming Structures
2.1. for loops
Programs for numerical simulation often involve repeating a set of commands many times. In
MATLAB, we instruct the computer to repeat a block of code by using a for loop. A simple
example of a for loop is
for i=1:10
repeats code for i=1,2,.
..,10
i
print out the value of the loop counter
end
This ends the section of code that is repeated.
The counter can be incremented by values other than +1.
for i=1:2:10
disp(i);
end
This example shows that the counter variables takes on the values 1, 3, 5, 7, 9. After 9, the
code next tries i=11, but as 11 is greater than 10 (is not less than or equal to 10) it does not
perform the code for this iteration, and instead exits the for loop.
for i=10:1:1
disp(i);
end
As the value of the counter integer is changed from one iteration to the next, a common use
of for blocks is to perform a given set of operations on different elements of a vector or a
matrix. This use of for loops is demonstrated in the example below.
Complex structures can be made by nesting for loops within one another. The nested for loop
structure below multiplies an (m x p) matrix with a (p x n) matrix.
A = [1 2 3 4; 11 12 13 14; 21 22 23 24];
A is 3 x 4 matrix
B = [1 2 3; 11 12 13; 21 22 23; 31 32 33];
B is 4 x 3 matrix
im = size(A,1);
m is number of rows of A
ip = size(A,2)
; p is number of columns of A
in = size(B,2);
n is number of columns of B
C = zeros(im,in);
allocate memory for m x n matrix containing 0's
now we multiply the matrices
for i=1:im
iterate over each row of C
for j=1:in
iterate over each element in row
for k=1:ip
sum over elements to calculate C(i,j)
C(i,j) = C(i,j) + A(i,k)*B(k,j);
end
end
end
C
print out results of code
A*B
MATLAB's routine does the same thing
clear all
2.2. if, case structures and relational operators
In writing programs, we often need to make decisions based on the values of variables in
memory. This requires logical operators, for example to discern when two numbers are equal.
Common relational operators in MATLAB are : eq(a,b) returns 1 if a is equal to b, otherwise it
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '07
 Gallivan
 Equals sign, relational operator, disp

Click to edit the document details