Introduction to MATLAB

advertisement
INC151 Electrical Engineering
Software Practice
Decision making:
Flow Control
1
In MATLAB, 5 control statements are





For loop
While loop
If-else-end construction
Switch case construction
Break statement
2
For Loops


For loop is used to repeat statements a specific
number of times.
The general format is
for variable = expression
statement
...
statement
end
>> for i=1:1:5
disp('I like MATLAB')
end
3
For Loops

More Examples
>>sum=0;
for i=0:1:10
sum=sum+i;
end
>>for n=1:10
x(n)=sin(n*2*pi/10);
end
4
>> n = 5;
for i=1:n
fprintf('%6d %8.4f\n',i,sqrt(i));
end
>> fprintf(' a (rad) d (deg) sin(a) cos(a)\n')
for a=0:pi/6:pi
d = a*180/pi; % convert from radian to degrees
fprintf('%8.3f %8.1f %9.4f %9.4f\n',a,d,sin(a),cos(a));
end
5
Exercise 1
Create forloopexercise.m contained for loops to
calculate the sum and average value of 5 inputs
[15 mins]
Example
>> forloopexersice
Enter input 1=10
Enter input 2=20
Enter input 3=30
Enter input 4=40
Enter input 5=50
The sum is 150.00 and average value is 30.00

6
Exercise 2

Write a for loop to duplicate each element of the
vector. Save with the name forloopexercise2.m.
[10 mins]
Example
>> A=[1 3 2 4];
>> forloopexercise2
1
1
3
3
2
2
4
4
7
While Loops


While loop is used when number of iteration is not known
beforehand.
The general format is
while expression
statement
...
statement
end
If expression is TRUE, statements will be executed.
>> i=1;
while i<10
i=i+1;
disp(i)
end

8
While Loops

More examples
9
Review: Relational and Logical Operator
10
Elementwise vs Expression
Logical operations, with short-circuiting capability
Syntax

expr1 && expr2
expr1 || expr2
represents a logical AND and OR operation that employs short-circuiting
behavior. With short-circuiting, the second operand expr1 is evaluated
only when the result is not fully determined by the first operand expr1.
For example, if A = 0, then the following statement evaluates to false,
regardless of the value of B, so MATLAB does not evaluate B:
i.e. while( (cont=='Y') || (cont=='y') )
Elementwise(Bitwise)
>>u = [0 0 1 1 0 1];
>>v = [0 1 1 0 0 1];
>>u | v
ans =
0 1 1 1 0 1

11
Conditional Expression











x=10;
y=20;
disp(x<y);
disp(x<= 10);
disp(x == y);
disp((0 < x) & (y < 30));
disp((x > 10) | (y > 100));
disp(~(x > 10));
area=[ 1 4 9 16 25 36 ];
perimeter=[ 4 8 12 16 20 24 ];
disp(area < perimeter);
% displays
% displays
% displays
% displays
% displays
% displays
1
1
0
1
0
1
% displays 1 1 1 0 0 0
12
Exercise 3
Create a while loop M-file(lift.m) used to give a warning
message if the total weight of persons in the lift is
overweighed(>500kg) as shown in the example [15 mins]
Example.

>>please enter the next person weight(kg)=75
please enter the next person weight(kg)=70
please enter the next person weight(kg)=85
please enter the next person weight(kg)=52
please enter the next person weight(kg)=100
please enter the next person weight(kg)=60
please enter the next person weight(kg)=40
please enter the next person weight(kg)=65
Buzzer sound!! Lift is overweight now !!!!
people in lift=7
total weight=482

13
Exercise 4
Create a while loop M-file(input1to10.m) used to ask
the user to input the number between 1 and 10 as
shown in the example [15 mins]
Example.
>>Please Enter a Number between 1 and 10 (1-10)20
Incorrect input, please try again.
Enter a Number between 1 and 10 (1-10)9
OK

14
Exercise 5(String Comparison)

Create a while loop M-file(enterSIunit10.m) used to
check the matching of ‘SI’ or ‘si’ string entering from
the user as shown in the example [15 mins]
Example.
>>enter unit=SSS
try again
enter unit=SI
ok. You enter the correct SI unit
>>enter unit=gu
try again
enter unit=metric
try again
enter unit=si
ok. You enter the correct SI unit
Hint . Try strcmp, strcmpi
15
Converting for to while loop
for x = 1:2:30
disp(x)
end
%%%%%%%%%%%%%%%%%%
x = 1; % STEP 1
while(x<=30) % STEP 2
disp(x)
x = x + 2; % STEP 3
end
16
If-else-end


Conditionally execute statements
The general format is
if expression
statement
else
if expression
statement
else
statement
end
end
Remarks else if, with a space
between the else and the if,
differs from elseif, with no
space. The former introduces a
new, nested if, which must have
a matching end. The latter is
used in a linear sequence of
conditional statements with only
one terminating end.
17
Examples
>>temp=input('enter the measured temperature:');
if temp<37
disp('normal condition')
else
disp('catch a fever')
end
>>attendance=input('enter the attendance:');
average_grade=input('enter the average_grade:');
if ((attendance>=0.9) & (average_grade>50))
disp('passed')
else
disp(‘failed')
end
18
Examples
>>value = input('Input value (0-100): ');
if value < 50
disp (' You got F');
elseif 50 <= value & value < 60
disp (' You got D');
elseif 60 <= value & value < 75
disp (' You got C');
elseif 75 <= value & value < 90
disp (' You got B');
else
disp ('You got A');
end
19
Switch case


Switch compares the input expression to each
case value. Once the match is found it executes
the associate statements.
The general format is
switch switch_expression
case(case1_expression)
statements
case(case2_expression)
statements
...
…
otherwise
statements
end
Remarks if/else is fine when
only a few options are present.
When a large number of
options are possible, it is
customary to use switch
construction instead. The
switch expression can be a
number or a string.
20
Switch case
-Calling function
>>x=30; %30 centimeter
>>units='feet‘;
>>switch1 %function name
21
Exercise 6

Use MATLAB to create a game called “Guess the number”. The
game will ask the player to guess the number between 0-10. The
dummy(answer) number is generated randomly(using rand round
command). If player failed 3 times, the game is over. After game
over, the game must ask the player whether he/she want to play
again. See the example for details.
[30 mins]
Example
>>mygame
Guess a number(0-10):5
Guess a number(0-10):7
Guess a number(0-10):2
You failed, Try again(Y/N)?
% player enter ’Y’ if ‘N’ quit a game
Guess a number(0-10):9
Yes, you got it!!!
22
End
23
Download