Chapter 4_Programming with Matlab_Part 2
Chapter 4_Programming with Matlab_Part 2
m: initial value
s: step value or incremental value
n: terminating value
k>n
True
?
Increment k
by s
False
Statements
End
Statements
following the
end statement Flow chart of a for loop
Ex:
for k = 5:10:35 for k = 5:10:35 , x = k^2 , end
x = k^2
end less readable
The loop variable k is initially assigned the value 5, and x is
calculated from x = k^2.
Each successive pass through the loop increment k by 10 and
calculates x until k exceeds 35.
k takes on the values 5, 15, 25 and 35 with the corresponding
values of x are: 25, 225, 625, and 1225.
The program then continues to execute any statements
following the end statement.
Rules when using for loops:
1. The step value s may be negative.
2. If s is omitted, the step value defaults to one.
3. If s is positive, the loop will not be executed if m is greater
than n.
4. If s is negative, the loop will not be executed if m is less than
n.
5. If m equals n, the loop will be executed only once.
6. If the step value s is not an integer, round-off errros can
cause the loop to execute a different number of passes than
intended.
When the loop is completed, k retains its last value.
Should not alter the value of the loop variable within the
statements.
Create a special square matrix that has ones in the first row and first
column, and whose remaining elements are the sum of two elements, the
element above and the element to the left, if the sum less than 20.
Otherwise, the element is the maximum of those two elements.
function A = specmat (n)
A = ones(n) % create the matrix
for r = 1:n % for row
for c = 1:n % for column
if(r>1)&(c>1)
s = A(r-1,c) + A (r, c-1);
if(s<20)
A(r,c)= s; % create the elements ≠ A(1,1)
else
A(r,c)=max(A(r-1,c),A(r,c-1));
end
end
end
end
Practice:
Write a program to produce the following matrices:
4 8 12
10 14 18
A=
16 20 24
22 26 30
1 3 57
3 6 0 0
B=
5 0 10 0
7 0 0 14
break command: terminates the loop but does not stop
the entire program.
for k = 1:10
x = 50 – k^2
if x<0
break
end
y=sqrt(x)
end
Logical False
expressio
n
True
Statements
(which
increment the
loop variable)
End
Statements
following the
end statement
Flow chart of a while loop
Ex: x=5;
5
while x<25 9
disp(x) 17
x=2*x-1;
end