Upload
leliem
View
220
Download
0
Embed Size (px)
Citation preview
MATLAB Programming LogicSee Chapter 7 of Gilat
Kipp MartinUniversity of Chicago
Booth School of Business
February 1, 2012
1
The M-files
The following m-files are illustrated in this lecture.
I relAndLogicOp.m
I ifThen.m
I looping.m
I quizscores.txt
2
Logical and Relational Operators
Relational Operators
< Less than<= Less than or equal to> Greater than>= Greater than or equal to== Equal∼= Not equal to
I the Equal (==) operator and Not Equal (∼=) notationdiffer in VBA and MATLAB
I understand the difference between = (assignment) and ==(logical test)
4
Logical and Relational Operators
Logical Operators
MATLAB Operator Name MATLAB Function
& AND and(A, B)| OR or(A, B)∼ NOT not(A)
I In MATLAB, True has value 1 and False value 0.
I In MATLAB nonzero elements evaluate to True and zeroelements to False.
5
Logical and Relational Operators
Relational Operators and Scalars
test1 = 7 > 8;
test2 = 7 <= 8;
test3 = 7==8;
test4 = 7~=8;
test1 = 0
test2 = 1
test3 = 0
test4 = 1
6
Logical and Relational Operators
Relational Operators and Arrays
% now compare arrays
A = [63 59 69 85 90 100 56];
B = [44 20 87 80 90 78 100];
test5 = A > B;
test6=A==B;
% now compare scalar and array
C = 88;
test7 = C <= A;
test5 = 1 1 0 1 0 1 0
test6 = 0 0 0 0 1 0 0
test7 = 0 0 0 0 1 1 0
7
Logical and Relational Operators
Logical Operators
test8 = -10 | 0;
test9 = -10 & 0;
test10 =10 & ~ 0;
D = [63 -59 69 0 90 0 0];
E = [0 0 1 0 1 1 0 ];
test11 = D & 7
test12 = D & ~E
test8 = 1
test9 = 0
test10 = 1
test11 = 1 1 1 0 1 0 0
test12 = 1 1 0 0 0 0 0
8
Logical and Relational Operators
An example of applying the logical operator > to matrix.
Matrix scores is matrix of 5 quiz scores for 16 students
scores = load(’quizscores.txt’);
% count scores on quiz 3 above 80
q3Above80 = scores(:,3)>80;
total = sum( q3Above80)
% which students scored above 80
find( q3Above80)’
total = 6
ans = 1 4 6 9 10 11
See the functions on page 198 of Gilat.
9
Logical and Relational Operators
That was pretty neat!
Instead of just counting scores 80 and above, how would we listthem?
Method 1:
scores = load(’quizscores.txt’);
q3Above80 = scores(:,3)>80;
q3Above80.*scores(:,3)
Method 2: Even better, only list the nonzeros, i.e. ones above 80.
scores = load(’quizscores.txt’);
q3Above80 = scores(:,3)>80;
scores(find( q3Above80),3)
10
If-Then Logic
See the MATLAB m-file ifThen.m. Here are few simple examplesof MATLAB if statements. (Note all key words are lower case.)
x = 10
if x > 0
fprintf(’The log of x is %f\n’, log(x))
end
x = 75
if x >= 50 & x <=100
discount_rate = .05;
fprintf(’The discount_rate is %f\n’, discount_rate)
end
11
If-Then Logic
Here is a comparison of MATLAB and VBA for the classicif-then-else block. Note that VBA is more verbose.
12
If-Then Logic
Here is an example of the if-then-else logic.
if x > 0
fprintf(’The log of x is %f\n’, log(x))
else
fprintf(’Please input a strictly positive number’)
end
13
If-Then Logic
Here is an example of if-then-elseif-else logic.
income = 5000
if income <=15100
tax = .10*income
elseif income <= 61300
tax = .15*income
elseif income <= 123700
tax = .25*income
elseif income <= 188450
tax = .28*income
elseif income <= 336550
tax = .33*income
elseif income > 336550
tax = .35*income
else
fprintf(’enter a valid number\n’)
end15
If-Then Logic
degree = ’MBA’;
switch lower( degree)
case {’mba’,’masters’}
disp(’this person has a masters degree’)
case ’phd’
disp(’this person has a Ph.D.’)
case ’md’
disp(’this person is a Doctor’)
otherwise
disp(’Unknown degree.’)
end
Unfortunately, in MATLAB there is not the equivalent of the Is keyword in VBA.
17
Looping
total = 0;
for i = 1:20
total = total + i^2;
end
I In the for loop, the statement
total = total + i ^ 2
is not an equality. It is an assignment statement. It replacesthe memory location that stores the variable total with thevalue that is currently in this memory location plus the valueof i2
I the end statement does two things:
I it increments the counter i by the amount of the step size(which is 1 by default)
I it returns control to the beginning of the loop (the forstatement)
20
Looping
Here are some examples where the step size is not 1.
Add squares of odd integers, the step size is 2.
total = 0;
for i = 1:2:20
total = total + i^2;
end
Now start at 19 and go down to 1 by -2
total = 0
for i=19:-2:1
total = total + i^2;
end
21
Looping
A while to add the odd integers from 1 to 20.
total = 0;
i = 1;
while i <= 20
total = total + i^2;
i = i + 2;
end
23
Looping
Something complicated – use nested loops to do bubble sort. Sortan array smallest to largest. Basic idea:
I At iteration i assume elements 1 through i-1 are alreadysorted smallest to largest
I Test element a(i). If, for some k ≤ i -1, a(i) ≥ a(k) thena(i) ≥ a(j) for all j = 1, . . ., k. We should not moveelements 1 through k.
I Assume k is the smallest index such that a(i) < a(k) and k≤ i -1.
I Shift elements k through i -1 one index to the right. Put a(i)in slot k.
24
Looping
a = [ 5 1 -77 1 9 11];
[m, n] = size( a) ;
for i = 2:n
found = false;
k = i - 1;
while k > 0 & a(i) < a(k)
k = k - 1;
found = true;
end
if found == true
tmp = a(i);
for j = i:-1:k+2
a(j) = a(j-1);
end
a(k+1) = tmp;
end
end25
Looping
break
I inside a loop break terminates execution of the loop andbegins executing the first line after the end statement (forexample, break out of the loop when we find the name we arelooking for)
I if we are not in a loop, break will terminate execution of them-file.
continue
I using this statement inside a loop, passes control to thecurrent loop end statement
26