cpet190_lect9
TRANSCRIPT
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 11
CPET 190 CPET 190
Problem Solving with MATLABProblem Solving with MATLAB Lecture 9Lecture 9
http://www.etcs.ipfw.edu/~linhttp://www.etcs.ipfw.edu/~lin
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 22
Lecture 9: MATLAB Program Design Lecture 9: MATLAB Program Design & Flow Control II& Flow Control II9-1 Control Flow – 9-1 Control Flow –
• if, else, elseif, endif, else, elseif, end• switch, case, otherwiseswitch, case, otherwise• forfor• whilewhile• break, continuebreak, continue
9-2 Loop Control9-2 Loop Control• forfor• whilewhile• break, continuebreak, continue
9-3 Conditional Statements9-3 Conditional Statements• if, else, elseif, endif, else, elseif, end
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 33
9-1 Control Flow9-1 Control FlowMATLAB Control Flow (keywords)MATLAB Control Flow (keywords)
• if, else, elseif, endif, else, elseif, end• switch, case, otherwiseswitch, case, otherwise• forfor• whilewhile• break, continuebreak, continue
Specifying conditions and selections Specifying conditions and selections • If, else, elseif, end If, else, elseif, end • switch-case statementsswitch-case statements
Repeating a set of commands or functions Repeating a set of commands or functions • ForFor• whilewhile
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 44
9-2 Loop Control9-2 Loop ControlFOR LoopFOR Loop FOR Repeat statements a specific number of times.FOR Repeat statements a specific number of times. The general form of a FOR statement is: The general form of a FOR statement is:
FOR FOR variable = n:s:mvariable = n:s:mstatement, ..., statement statement, ..., statement
ENDEND where where variablevariable is the loop counter, is the loop counter, nn is the initial is the initial
value, value, ss is the loop counter increment or decrement is the loop counter increment or decrement size, size, mm is the final value is the final value
Example:Example: for n = 1:10for n = 1:10
statement 1statement 1 statement 2statement 2
.... statement nstatement n endend
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 55
9-2 Loop Control9-2 Loop ControlExample 9-1: Nested For LoopsExample 9-1: Nested For Loops
% multiplytable.m% multiplytable.mN = 9; N = 9; A = zeros(N);A = zeros(N);for row = 1:N,for row = 1:N, for col = 1:N,for col = 1:N, A(row, col) = A(row, col) =
row * col;row * col; endendendenddisp(A)disp(A)
1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 66
9-2 Loop Control9-2 Loop Control
Example 9-2: While loopExample 9-2: While loop
%whileloop.m%whileloop.mn = 1;n = 1;while n < 6while n < 6 disp(n)disp(n) n = n + 1;n = n + 1;endend
Output:
1
2
3
4
WHILE Loop - WHILE Loop - WHILE Repeat statements an indefinite number WHILE Repeat statements an indefinite number of times.of times.
The general form of a WHILE statement is: The general form of a WHILE statement is: WHILE expressionWHILE expression statementsstatementsENDEND
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 77
9-2 Loop Control9-2 Loop ControlTerminate Loop or Exit Conditional StatementsTerminate Loop or Exit Conditional Statements
• BreakBreak – stop execution of loop – stop execution of loop • Continue – Exit the inner loop and continuing on outer loopContinue – Exit the inner loop and continuing on outer loop
Example 9-3Example 9-3%break_continue.m%break_continue.mk = 1;k = 1;while k < 10while k < 10 x = 10 - k^2;x = 10 - k^2; if x < 0if x < 0 breakbreak endend y = sqrt(x)y = sqrt(x) k = k + 1;k = k + 1;endendfprintffprintf('The %d time in the loop -> x less than zero = %d\n', k, x);('The %d time in the loop -> x less than zero = %d\n', k, x);%The 4th time in the loop -> x %less than zero = -6%The 4th time in the loop -> x %less than zero = -6
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 88
9-2 Loop Control9-2 Loop ControlContinue StatementContinue Statement
• Continue – Pass control to the next iteration of Continue – Pass control to the next iteration of the FOR or WHILE loopthe FOR or WHILE loop
Example 9-4Example 9-4%continue_ex.m%continue_ex.mfor k=1:6for k=1:6 if k == 4;if k == 4; continuecontinue endend fprintf('k = %d\n', k); fprintf('k = %d\n', k); endenddisp('End of loop')disp('End of loop')
Output:Output:k = 1k = 1k = 2k = 2k = 3k = 3k = 5k = 5k = 6k = 6End of loopEnd of loop
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 99
9-3 Conditional Statements9-3 Conditional Statements Three Forms of if StatementsThree Forms of if Statements
• if-endif-end• if-else-endif-else-end• if-elseif-else-endif-elseif-else-end
IF- END format IF- END format • Single statementSingle statement
if conditionif condition statementstatementendend
• Multiple statementsMultiple statementsif conditionif condition
Statement_1;Statement_1; Statement_2;Statement_2; … ….. Statement_n;Statement_n;end end
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1010
9-3 Conditional Statements9-3 Conditional Statements
Example 9-5: compute only if x Example 9-5: compute only if x ≥ 0.≥ 0.
%inf_cond1.m%inf_cond1.mx = input('Enter a number: ')x = input('Enter a number: ')y_complex = y_complex = sqrt(x)sqrt(x)if x >= 0if x >= 0 y_real = y_real = sqrt(x)sqrt(x)endend% x = 2 % x = 2 % y_complex = 1.4142 % y_complex = 1.4142 % y_real = 1.4142% y_real = 1.4142% x = -2% x = -2% y_complex = 0 + 1.4142i% y_complex = 0 + 1.4142i
xy
Real Axis
Imaginary Axis
I or J operator90 degree
0 + 1.4142 j
1.4142
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1111
9-3 Conditional Statements9-3 Conditional Statements Example 9-6: A Grade Calculation Program – Example 9-6: A Grade Calculation Program –
Problem StatementProblem Statement
Compute average grade of three exams (input from Compute average grade of three exams (input from keyboard), then calculate and print a letter grade (on keyboard), then calculate and print a letter grade (on the screen) based on the following policy:the screen) based on the following policy:
A grade: Average >= 90A grade: Average >= 90B grade: 80 <= Avg < 90B grade: 80 <= Avg < 90C grade: 70 <= Avg <80C grade: 70 <= Avg <80D grade: 60 <= Avg < 70D grade: 60 <= Avg < 70F grade: Avg < 60F grade: Avg < 60
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1212
9-3 Conditional Statements9-3 Conditional Statements Example 9-6: A Grade Calculation Program – using Example 9-6: A Grade Calculation Program – using
FlowchartFlowchartStart
Avg >=90
80 <= Avg < 90
70 <= Avg < 8070 <= Avg < 80
60 <= Avg < 70
Avg < 60
End
Input T1, T2, and T3 Scores; Compute Average
Grade = ‘A’, Print
Grade = ‘B’, Print
Grade = ‘C’, Print
Grade = ‘D’, Print
Grade = ‘F’, Print
No
No
No
No
Yes
Yes
Yes
Yes
Yes
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1313
9-3 Conditional Statements9-3 Conditional Statements Example 9-6: A Grade Calculation Program – SolutionExample 9-6: A Grade Calculation Program – Solution
%grade_prog.m%grade_prog.mt1 = input('Enter Test 1 Score: ')t1 = input('Enter Test 1 Score: ')t2 = input('Enter Test 2 Score: ')t2 = input('Enter Test 2 Score: ')t3 = input('Enter Test 3 Score: ')t3 = input('Enter Test 3 Score: ')% Grade calculation% Grade calculation
avg = (t1 + t2 + t3)/3;avg = (t1 + t2 + t3)/3;if avg >= 90 if avg >= 90 Grade = 'A';Grade = 'A';endendif (avg >= 80) & (avg < 90) if (avg >= 80) & (avg < 90) Grade = 'B';Grade = 'B';endend
if (avg >= 70) & (avg < 80) if (avg >= 70) & (avg < 80) Grade = 'C';Grade = 'C';endendif (avg >= 60) & (avg < 70) if (avg >= 60) & (avg < 70) Grade = 'D';Grade = 'D';endendif avg < 60if avg < 60 Grade = 'F';Grade = 'F';endendfprintf('Your average score fprintf('Your average score is %g.\n', avg);is %g.\n', avg);fprintf('Your grade grade is fprintf('Your grade grade is %c.\n', Grade);%c.\n', Grade);
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1414
9-3 Conditional Statements9-3 Conditional Statements
IF-ELSEIF-ELSE-END IF-ELSEIF-ELSE-END ifif expression expression statementsstatementselseif elseif expressionexpression statementsstatementselseelse statementsstatementsendend
ifif expression expression statements_1statements_1 elseifelseif statements_2statements_2 elseifelseif statements_3statements_3 elseelse statements_4statements_4 endend
IF-ELSE-ENDIF-ELSE-END Construct: Construct: if if expression expression statements_1statements_1elseelse statements_2statements_2endend
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1515
9-3 Conditional Statements9-3 Conditional Statements
Example 9-7: A Full Wave RectifierExample 9-7: A Full Wave Rectifier
AC 60HzSine wave
RL = 100 ohms
VL
51 2 3
4
6
7
8910
10V110V
Transformer
Bridge Rectifier
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1616
9-3 Conditional Statements9-3 Conditional Statements
Example 9-7: A Full Wave Rectifier Example 9-7: A Full Wave Rectifier Simulation using IF-END and FOR loop.Simulation using IF-END and FOR loop.
Pusedocode Pusedocode Transformer voltage ratio 110/10 voltsTransformer voltage ratio 110/10 volts e1 = 10*sin(2*pi*f*t); f = 60Hze1 = 10*sin(2*pi*f*t); f = 60Hz Rectifying signal e1Rectifying signal e1
If e1 < 0If e1 < 0 e1 = -e1;e1 = -e1;endend
Output – Full-wave rectified voltage (plot)Output – Full-wave rectified voltage (plot)
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1717
9-3 Conditional Statements9-3 Conditional StatementsExample 9-7: SolutionExample 9-7: Solution
%full_rec.m%full_rec.m% Primary side voltage% Primary side voltageVp = 110; Vp = 110; % secondary side voltage% secondary side voltageVs = 10; Vs = 10; % Frequency is 60 Hz% Frequency is 60 Hzf = 60; f = 60; % Period is 16.67 ms% Period is 16.67 msT = 1/f; dt = 10E-3*T;T = 1/f; dt = 10E-3*T;% For showing 2 cycles% For showing 2 cyclest = 0:dt:T; e1 t = 0:dt:T; e1
=Vs*sin(2*pi*f*t);=Vs*sin(2*pi*f*t);len = length(e1);len = length(e1);
% Rectifier operation% Rectifier operationfor n = 1: len,for n = 1: len, if e1(n) >= 0if e1(n) >= 0 e2(n) = e1(n);e2(n) = e1(n); elseelse e2(n) = -e1(n);e2(n) = -e1(n); endendendend
% continue on next % continue on next % slide% slide
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1818
9-3 Conditional Statements9-3 Conditional StatementsExample 9-7: Solution (cont.)Example 9-7: Solution (cont.)%full_rec.m%full_rec.mfigure(1), plot(t, e2, 'r', t, e1,'b--'), figure(1), plot(t, e2, 'r', t, e1,'b--'),
grid ongrid ontitle('Full Wave Rectifier')title('Full Wave Rectifier')xlabel('Time in sec')xlabel('Time in sec')ylabel('Volts')ylabel('Volts')
figure(2), subplot(2,1,1), plot(t, e1), figure(2), subplot(2,1,1), plot(t, e1), grid ongrid on
title('Input signal')title('Input signal')xlabel('Time in sec')xlabel('Time in sec')ylabel('Volts')ylabel('Volts')figure(2), subplot(2,1,2), plot(t, e2), figure(2), subplot(2,1,2), plot(t, e2),
grid ongrid ontitle('Full Wave Rectified Signal')title('Full Wave Rectified Signal')xlabel('Time in sec')xlabel('Time in sec')ylabel('Volts')ylabel('Volts')
0 0.002 0.004 0.006 0.008 0.01 0.012 0.014 0.016 0.018-10
-5
0
5
10Input signal
Time in sec
Volts
0 0.002 0.004 0.006 0.008 0.01 0.012 0.014 0.016 0.0180
2
4
6
8
10Full Wave Rectified Signal
Time in sec
Volts
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 1919
SummarySummary Control FlowControl Flow Loop ControlLoop Control
• forfor• whilewhile• break, continuebreak, continue
Conditional StatementsConditional Statements• if, else, elseif, endif, else, elseif, end
Next - Multiple Decision using switch, Next - Multiple Decision using switch, case, whatever, endcase, whatever, end
And More applicationsAnd More applications
February 14, 2005February 14, 2005 Lecture 9 - By Paul LinLecture 9 - By Paul Lin 2020
Question?Question?
AnswersAnswers
Email: [email protected]: [email protected]