Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017
Outline
Loop statements
Program Flow Control
for loop
forstatementisusedasacountedloop,allowingtorepeatanactiona
specified number of times
Aniteratororloopvariablespecifieshowmanytimestorepeatthe action
Generalform:
for loopvar = range action
end
Therangeisspecifiedbyavectororamatrix
Theactionisrepeatedforeveryvalueoftheloopvariableinthe
specified range
Commontypesoffor-loops
valcanalsobeamatrix
Examples
Loopthatusestheiteratorvariable:
for i = 1:3
fprintf(’i is %d\n’, i)
end
i is 1
i is 2
i is 3
Loopthatdoesnotusetheiteratorvariable:
for i = 1:3
disp(’Hello’)
end
Hello
Hello
Hello
Examples
k1 = [1,2,3,4,5];
for k = k1
x = 3.0 + 0.1*k
end
x=
3.1000
x=
3.2000
x=
3.3000
x=
3.4000
x=
3.5000
k1 = [1; 2; 3; 4; 5];
for k = k1
x = 3.0 + 0.1*k
end
x=
3.1000
3.2000 3.3000 3.4000 3.5000
for k = 1:5
x = 3.0 + 0.1*k
end
x=
3.1000
x=
3.2000
x=
3.3000
x=
3.4000
x=
3.5000
k1 = [1; 2; 3]; k2 = [4; 5; 6];
for k = [k1, k2] x = 3.0 + 0.1*k
end
x=
3.1000
3.2000
3.3000 x=
3.4000 3.5000 3.6000
Standard for-loops uses
Thesumofelementsofarowvector
% first solution
mysum = 0; for i = v
mysum = mysum + i;
end
% second solution
mysum = 0;
for i = 1:length(v)
mysum = mysum + v(i);
end
Theproductofelementsofarowvector
% first solution
myprod = 1; for i = v
myprod = myprod*i;
end
% second solution
myprod = 1;
for i = 1:length(v)
myprod = myprod*v(i);
end
Don’tforget:InMATLAB,thesimplestwaytocalculatethe sum/product of a vector v is to call sum(v)/prod(v)
Combining for loops and if
forloopsandifstatementscanbecombined
the action of a loop can include an if statement
g = [92, 45, 90, 80, 94, 75]; count = 0;
for k = 1:length(g)
if g(k) >= 90 % or, more simply, replace
count = count + 1; % if-end statements by
end % count=count + (g(k)>=90);
end
disp(count) 3
the action of an if statement can include a for loop
case = 2;
N = 1000; S = 0;
if case == 2 for k = 2:2:N
S = S + 1/k^2;
end
elseif case == 1
for k = 1:2:N
S = S + 1/k^2;
end else
% sum over even k’s
% sum over odd k’s
disp(’case must be 1 or 2’);
end
Standard combined for-if uses Theminimumoftheelementsofavector
% first solution
mymin = Inf;
for i = v
if i < mymin
mymin = i;
end end
% second solution
mymin = v(1);
for i = 2:length(v)
if v(i) < mymin
mymin = v(i);
end end
Nested for-loops
Anestedforloopisoneinsideof(astheactionof)anotherforloop
Generalform:
for loopvar_1 = range_1 action_1
for loopvar_2 = range_2
action_2
end end
% outer loop
% inner loop
Theinnerloopactionisexecutedinitsentiretyforeveryvalueoftheouterloop variable
N = 4; M = 3;
for i = 1:N % loop over the rows
for j = 1:M
A(i,j) = i+j;
end end
»A A=
% loop over the columns
234 345 456 567
while loop
whilestatementisusedasaconditionalloop,allowingtorepeatan action when ahead of time it is not known how many times the action will be repeated
Generalform:
while condition action
end
Theactionisrepeatedaslongastheconditionistrue
N=1000; S=0; k=1;
while k <= N
S = S + 1/k^2;
k = k+1;
end
Aninfiniteloopcanoccuriftheconditionneverbecomesfalse(UseCtrl-Cto break out of an infinite loop)
Note:sincetheconditioncomesbeforetheaction,itispossiblethatthecondition will be false the first time it is evaluated and therefore the action will not be executed at all
Example
Error-checking using while loop
Withmostuserinput,thereisavalidrangeofvalues
Awhileloopcanbeusedtokeeppromptingtheuser,readingthe value, and checking it, until the user enters a value that is in the correct range
Generalformofawhileloopthaterror-checks:
prompt user and input value
while value is not in correct range
print error message
prompt user and input value
end
use value
Example
radius = input(’Enter the radius of a circle: ’);
while radius <= 0
radius = input(’Invalid! Enter a positive radius: ’);
end
area = pi * radius ^2;
fprintf(’The area is %.2f\n’, area)
Example
Considerascriptcheck_grade.mthatwillprompttheuserforaquiz grade and error-check until the user enters a valid quiz grade. The script will then print the grade. The valid grades are in the range from 1 to 6 in steps of 0.5.
Method: create a vector of valid grades and then do 3 solutions: using any, all, and find.
Solutionusingany
fprintf(’Valid quiz grades are in the range from ’)
fprintf(’1 to 6 in steps of 0.5\n’)
valid_grade = 1:0.5:6;
quiz = input(’Enter a quiz grade: ’);
while ~any(quiz == valid_grade)
quiz = input(’Invalid! Enter a quiz grade: ’);
end
fprintf(’Cool, the grade is %.1f\n’, quiz)
Example
Solutionusingall
fprintf(’Valid quiz grades are in the range from ’)
fprintf(’1 to 6 in steps of 0.5\n’)
valid_grade = 1:0.5:6;
quiz = input(’Enter a quiz grade: ’);
while all(quiz ~= valid_grade)
quiz = input(’Invalid! Enter a quiz grade: ’);
end
fprintf(’Cool, the grade is %.1f\n’, quiz)
Solutionusingfind
fprintf(’Valid quiz grades are in the range from ’)
fprintf(’1 to 6 in steps of 0.5\n’)
valid_grade = 1:0.5:6;
quiz = input(’Enter a quiz grade: ’);
while isempty(find(quiz == valid_grade))
quiz = input(’Invalid! Enter a quiz grade: ’);
end
fprintf(’Cool, the grade is %.1f\n’, quiz)
Counting in a while loop
Itisfrequentlyusefultocounthowmanytimestheactionofthe loop has been repeated
Generalformofawhileloopthatcounts:
counter = 0;
while condition
% action
counter = counter + 1;
end
% use counter - do something with it!
break, continue Statements
breakstatementterminatesexecutionofaloop,andcontinuesafter the end of the loop
break terminates out of a nested loop only !
continuestatementstopspresentpassthroughaloop,butcontinues
with next pass Examples:
for i = 1:5
if i == 3
continue;
end
fprintf(’i = %d\n’, i);
end
i=1 i=2 i=4 i=5
for i = 1:5
if i == 3
break; end
fprintf(’i = %d\n’, i);
end
i=1 i=2
Example forever while - loops Generalform:
while 1 statements ... if condition
break; end
statements ...
end
Example
N=1000; S=0; k=1;
while 1
S = S + 1/k^2;
if k > N
break; end
k = k+1;
end
» S,k S=
1.6439 k=
1000
Sum of a series
Considerthefollowinginfiniteseries:
S = ∞ ( − 1 ) k
(2k + 1)3k k=0
InMATLAB,wemaycalculateonlyfinitesums
n (−1)k
Sn = We can re-write Sn as:
(2k+1)3k, withn≥0 (−1)k (−1)n
n−1 k=0
k=0
Sn =
ThereforeSn =Sn−1 +Tn,∀n≥1,andS−1 =0,T0 =1
(2k+1)3k +(2n+1)3n =Sn−1+Tn
Sum of a series
Usingfor-loops
N = 10000;
S = 0;
tol = 1e-14;
% max number of iterations
% initialize sum
% relative error
for n=0:N
T = (-1)^n /(2*n+1)/3^n; % n-th term
if abs(T) < tol % break out of the for-loop
break; %if T is small
end
S = S + T; % update sum
end
Usingwhile-loops
n = 0;
S = 0;
T = 1;
tol = 1e-14;
% index of the first term
% initialize sum
% value of the first term
% relative error
while abs(T) > tol
S =S+T; % update sum
n =n+1; % update index
T = (-1)^n /(2*n+1)/3^n; % n-th term
end
To remember …
BewareofCommonPitfalls
Forgetting to initialize a running sum or count variable to 0 or a running product to 1
Not realizing that it is possible that the action of a while loop will never be executed
Not error-checking input into a program
Not taking advantage of MATLAB pre-defined vector functions
(sum, prod, min, max, .. ProgrammingStyleGuidelines
Do not use i or j for iterator variable names if the use of the built-in constants i and j is desired.
Indent the action of loops
If the loop variable is just being used to specify how many times
the action of the loop is to be executed, use the colon operator
1:n