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
repeats code for i=1,2,.
print out the value of the loop counter
This ends the section of code that is repeated.
The counter can be incremented by values other than +1.
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.
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
iterate over each row of C
iterate over each element in row
sum over elements to calculate C(i,j)
C(i,j) = C(i,j) + A(i,k)*B(k,j);
print out results of code
MATLAB's routine does the same thing
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