Looping!
• Scripts and functions also allow the ability to loop using conventional for and while loops.
• Note that the interpreter also lets you do it, it is simply less easy to grasp
For Loops
• Common to other programming languages
for variable = expression
statement
...
statement
end
For Loops, con’t: 2
• Example: (taken from MATLAB help)
• a = zeros(k,k) % Preallocate matrix for m = 1:k
for n = 1:k a(m,n) = 1/(m+n -1);
end end
For Loops, con’t: 3
• The looping variable is defined in much the same way that we defined arrays/vectors.
• Ex. m = 1:k
• Or m = 1:10
For Loops, con’t: 4
• Loops are shown to end by the keyword “end”
• Curly braces are not present to subdivide packets of code
• Make use of adequate white-space and tabbing to improve code readability
LOGICAL CONTROL PROGRAMMING CONSTRUCTS
• Syntax of the if statement:
if logical expression
statements
end
LOGICAL PROGRAMMING CONTRUCTS
• Nested “if” statements:
if logical expression 1 statement group 1
if logical expression 2statement group 2
endend
• Note the indentions
Nested Statement
LOGICAL PROGRAMMING CONTRUCTS
THE else STATEMENT:If two mutually exclusive actions can occur as a result of
a decision, use the else statement.
if logical expression statement group 1
else statement group 2
end
In-class Exercise (5 minutes)
• Suppose y = x1/2 for x >= 0
and y = ex – 1 for x < 0
• Write a program (.m script file) to calculate y assuming that x already has a scalar value.
• Test your program for x = 3 and x = -2.
SOLUTION (Script File)
% Solution to In-Class Exercise
if x >= 0
y = sqrt (x);
else
y = exp (x) -1;
end Did you indentproperly?!
LOGICAL PROGRAMMING CONSTRUCTS
The elseif statement:
When three actions can occur as a result of a decision, the else and elseif statements are used along with the if statement.
Remember: ONLY ONE ACTION WILL ACTUALY OCCUR!!!
LOGICAL PROGRAMMING CONSTRUCTS
if logical expression 1 statement group1elseif logical expression 2 statement group 2else statement group 3end
EXAMPLE
Given:
y = ln x for x > 10
y = x1/2 for x >= 0 and x <= 10
y = ex – 1 for x < 0
Compute y if x has been assigned a scalar value.
SOLUTION (Script file)
% Solution to example
if x > 10
y = log (x)
elseif x >= 0
y = sqrt (x)
else
y = exp (x) -1
end
Does the order that I check things matter?YES!
LOGICAL PROGRAMMING CONSTRUCTS
Write the syntax for the if-elseif-else-end construct if there are more than three alternatives.