clear; clc; close ; format ; all

advertisement
clear; clc; close all; format shortg;
%Today we learn conditional statements and loops
%The conditional statement is an the if ... end statement
%It has three varieties,
%(1) if ... end
%(2) if ... else ... end
%(3) if ... elseif ... else ... end
%(1) if ... end
Test_Scores = [50 79 81]; Average = mean(Test_Scores);
if Average < 60
disp('Class grade = F.')
end
if (Average >= 60)&(Average < 70)
disp('Class grade = D.')
end
if (Average >= 70)&(Average < 80)
disp('Class grade = C.')
end
if (Average >= 80)&(Average < 90)
disp('Class grade = B.')
end
if Average >= 90
disp('Class grade = A.')
end
%(2) if ... else ... end
if Average >= 70
disp('Pass')
else
disp('Fail')
end
%(3) if ... elseif ... else ... end
Final = 85; Avg = 65;
if Avg >= 70
disp('Pass')
elseif Final >= 90
disp('Pass')
else
disp('Fail')
end
%Loops
%There are two types of loops
%(1) for ... end
%(2) while ... end
%(1) for ... end
for i = 1:10
x(i) = 2*i;
%No initialization required, runs 10 times
1
end
fprintf('x = ');
disp(x);
%(2) while ... end
i = 1;
while i < 11
y(i) = 3*i;
i = i+1;
end
fprintf('y = ');
disp(y);
%I have to initialize the indexing variable
%note I have to keep the indexing going
%Loops are used when you want to repeat the same command over and over
%But they're most useful when you nest conditional statements inside
%Example, what's your quiz average after your TA drops the lowest score
Quiz = [9 7.5 0 10 3 7 6 5.5 8 10 3.5];
drop = Quiz(1);
j = 1;
for i = 2:11
if Quiz(i) < drop
x(j) = drop;
drop = Quiz(i);
j = j+1;
else
x(j) = Quiz(i);
j = j+1;
end
end
fprintf('Quiz average is %g',mean(x))
%Nesting loops
%Often you'll nest both loops and conditionals
%Example how many integers both between 1 and 15 have sum divisible by 19?
%Display both the numbers and the sum (no repeats)
n = 0; i = 1;
for a = 1:15
for b = a:15
y = mod(a+b,19);
if y == 0
A(i,1) = a;
A(i,2) = b;
A(i,3) = a+b;
i = i+1;
end
end
end
disp(A)
%Hints
%Page 180 - 184 have different logic operators and a useful example problem
%Page 200-202 has another useful example problem
%Stuck? Write out the flow chart for the first few iterations of your loop
2
%Go back to old chapters to search for useful functions
%Page 14-15
%Page 76-77
%Appendix starting on page 393 has many useful commands and functions
Class grade = C.
Pass
Fail
x =
2
4
6
8
10
12
14
16
18
20
y =
9
12
15
18
21
24
27
30
3
6
Quiz average is 6.95
5
14
19
6
13
19
7
12
19
8
11
19
9
10
19
4
Published with MATLAB® R2014a
3
15
19
Download