Vous êtes sur la page 1sur 23

ESG

111
Programming for Engineers
WEEK 4
Conditional Statement, IF & ELSE


Maya K Endoh

Recall Rela'onal Expressions


The rela'onal operators in MATLAB are:
> greater than
< less than
>= greater than or equals
<= less than or equals
== equality
~= inequality
The resul'ng type is logical 1 for true or 0 for false
The logical operators are:
|| or for scalars, | or for array
&& and for scalars, & and for array
~ not
Also, xor func'on which returns logical true if only one of the
arguments is true

If Statement
The if statement is used to determine whether or not a
statement or group of statements is to be executed
General form:
if condi&on
ac&on
end

the condi&on is any rela'onal expression (logically true or


false)
the ac&on is any statements which will be executed if the
condi'on is true
the ac'on could be any number of valid statements un'l
the reserved word end
if the condi'on is true, the ac'on is executed otherwise, it is
skipped en'rely
if statement can be entered in the Command Window, but
more useful in the script or the func'on

Ex) checking nega've/posi've number


check_neg_pos.m
%check the negative/positive number
num=input('Please enter a number: ');
%{
If the user enter a negative number,
tell the user and change it to the absolute value
%}

Check the
dierence
between disp
and fprinY

if num<0
disp('The number is changed to the absolute value, as it is
negative')
num=abs(num);
end
Will be used to check the entered values sign to run the
dierent script or func'on

Swap: Exchanging values of variables


swap is useful when the value of one variable
needs to exchange with the other value in certain
condi'on
if statement is used to determine whether swap is
necessary or not
A temporary variable is necessary for swapping
Algorithm to exchange values of variables a and b:
Assign the value of a to temp
Same algorithm that
were performed for
Assign the value of b to a
swapping the two
Assign the value of temp to b
wine glasses

Exercise (from week3)


Write a script that will calculate the volume of
a hollow sphere,
4
V
=
(r r )

3
Where ri is the inner radius and ro is the outer
radius. Assign a value to a variable for the inner
and outer radius
3
o

Sample solu'on
%This script calculates the volume of a hollow sphere
%prompts the user for the radius
What IF riro ?!
ri = input('Enter the inner radius: ');
ro = input('Enter the outer radius: ');
volume= 4/3 * pi * (ro^3 - ri^3);
volume=fn_hol_vol_chap3(ri,ro);
fprintf('The hollow volume of inner radius of %.2f and outer radius of
%.2f is\n',ri,ro)
fprintf('%.2f.\n',volume)

function hol_vol=fn_hol_vol_chap3(ri, ro)


% Calculates the volume of a hollow sphere
hol_vol = 4/3 * pi .* (ro.^3 ri.^3);
end

Ex) Exchanging values of variables


in use-dened func'on
function hollvol=fn_vol_hol_sphere(ra, rb)
% Calculates the volume of a hollow sphere
%exchanging the value between ra and rb if ra>rb
if ra>rb
temp=ra;
ra=rb;
rb=temp;
end
% Calculates the volume of a hollow sphere
% rb is ALWAYS lager than ra
hollvol = 4/3 * pi * (rb^3 - ra^3);
end

Represen'ng true/false concepts


When character or number is used in the logical
sentence, any nonzero value can be used to represent
the concept of true
This can lead to some common logical errors
For example, the following expressions are always true
>> number=7;
>> if number<5||6
disp(yes')
end
yes

7<5 or
nonzero value
which represent
true

If sentence is
TRUE

>> number<5||number>0

>> if number<5||0
disp('yes')
end

TRUE or FALSE?

7<5 or zero
value which
represent false

If sentence is
FALSE
Thus skipped

If-else Statements
The if-else statement chooses between two ac'ons
General form:
if condi'on
One and only one ac'on is
TRUE
ac'on1
executed
else
which one depends on the
FALSE
value of the condi'on
ac'on2
ac'on1 if it is logical true
end
ac'on2 if it is false

Ex) error-checking
Check for errors in the input to a script
Check that the user enters invalid/valid value for the script
Chose the ac'on by if-else statement

Nested if-else Statements


To choose from more than two ac'ons, nested if-else
statements can be used (an if or if-else statement as the
ac'on of another)
General form:
if condi'on1
ac'on1
else
if condi'on2
ac'on2
else
if condi'on3
ac'on3
% etc: there can be many of these
else
ac'onn % the nth ac'on
end
end
end

condition3

condition2

condition1

The elseif clause


MATLAB also has an elseif clause which shortens the code (and cuts
down on the number of ends)
General form:
condition1
condition2

conditionN

if condi'on1
ac'on1
elseif condi'on2
ac'on2
elseif condi'on3
ac'on3
% etc: there can be many of these
else
ac'onn % the nth ac'on
end

Compare with
nested if-else
statement

Ex) In order to calculate the volume of


hollow sphere with radii ra & rb

ra > rb
ra < rb
ra = rb
ra and rb should be posi've value!

Sample solu'on ~if-else statement


%This script calculates the volume of a hollow sphere
%prompts the user for the radius
%nested if-else statement
radius = input('Enter the values of two radii: ');
%ra = input('Enter the value of radius: ');
%rb = input('Enter the value of radius: ');
clear volume
if any(radius<=0)
disp('Please enter the positive value!')
disp('Re-enter the values!')
else
%If we are here, the values of radii are positive
if radius(1)==radius(2)
disp('Both entered values are same!')
disp('Re-enter the values!')
else
%If we are here, the values of radii are not same
if radius(1)>radius(2)
temp=radius(1);
radius(1)=radius(2);
radius(2)=temp;
end
volume= 4/3 * pi * (radius(2)^3 - radius(1)^3);
fprintf('The hollow volume of radius of %.2f and %.2f is\n',radius)
fprintf('%.2f.\n',volume)
end
end

Sample solu'on ~if-elseif statement


%This script calculates the volume of a hollow sphere
%prompts the user for the radius
%if-elseif statement
radius = input('Enter the values of two radii: ');
%ra = input('Enter the value of radius: ');
%rb = input('Enter the value of radius: ');
clear volume
if any(radius<=0)
disp('Please enter the positive value!')
disp('Re-enter the values!')
elseif radius(1)==radius(2)
disp('Both entered values are same!')
disp('Re-enter the values!')
elseif radius(1)>radius(2)
temp=radius(1);
radius(1)=radius(2);
radius(2)=temp;
volume= fn_hol_vol_chap4(radius);
fprintf('The hollow volume of radius of %.2f and %.2f is\n',radius)
fprintf('%.2f.\n',volume)
else
volume= fn_hol_vol_chap4(radius);
fprintf('The hollow volume of radius of %.2f and %.2f is\n',radius)
fprintf('%.2f.\n',volume)
end

The switch case Statement


The switch statement can frequently be used in place of a nested if
statement
General form:

switch (switch_expression)
case {caseexp1}
switch_expression=caseexp1
ac:on1
case {caseexp2}
ac:on2
A case_expression cannot
case {caseexp3}
include rela'onal operators
ac:on3
such as <, or, > for comparison
% etc: there can be many of these
against the switch_expression.
otherwise
To test for inequality, use if,
ac:onN
elseif, else statements.
end
this can be used when comparing the switch_expression to see if it is equal to the
values on the case labels (the otherwise clause handles all other possible values)

EX)
Write a script that will prompt the user for a temperature in
Celsius, and convert to either Fahrenheit or to Kelvin.
The script will print the corresponding temperature in the scale
specied by the user (either F or K). For example, the output
might look like this:
Enter the temp in degrees C: 29.3
Do you want K or F? F
The temp in degrees F is 84.7

The format of the output should be exactly as specied above.


The conversions are:
9

F = C + 32
5
K = C + 273.15

Sample Solu'on
temp_convert.m
% Converts a temperature from C to F or K
cel = input('Enter the temp in degrees C: ');
choice = input('Do you want F or K? ', 's');
clear temperature;
switch choice
case {'F','f'}
temperature=fn_CtoF(cel);
fprintf('The temp in degrees F is %.1f\n', temperature)
case {'K', 'k'}
temperature=fn_CtoK(cel);
fprintf('The temp in degrees K is %.1f\n', temperature)
otherwise
disp('Unknown Units. Please re-enter')
end
fn_CtoF.m

fn_CtoK.m

function F=fn_CtoF(C)

function K=fn_CtoK(C)

%fn_CtoFconverts temperature from Celsius to Fahrenheit

%fn_CtoFconverts temperature from Celsius to Fahrenheit

F=(9/5).*C+32;

K=C+273.15;

end

end

The menu func'on


The menu func'on displays a menu of push-buqons, and
returns the result of the buqon push
myresult=menu(title,label#1,label#2,label#3)
- 'tle is the heading for the menu gure window
- label#1 is for the name of the f1st buqon, label#2 is for
the 2nd, etc.
- result of label#1 reserves value 1, label#2 reserves value 2,
and is stored in the variable myresult
- or 0 if no buqon is pushed
push-buqons will be displayed in the Figure Window for the
op'ons
a switch or nested if statement is used to perform dierent
ac'ons based on the menu op'ons

Example using menu


What we want is a script that prompts the
user for a value of a variable x. Then, it uses
the menu func'on to present choices
between sin(x) , cos(x) , and tan(x) .
The script will print whichever func'on of x
the user chooses. We will do this using two
methods to make the choice:
if-else
switch

Solu'on using if-else


% Prints either sin, cos, or tan of x
% uses the menu function to choose
x = input('Enter a value for x: ');
choice = menu('Choose a function, 'sin','cos','tan,quit);
if choice == 1
fprintf('sin(%.1f) is %.1f\n', x, sin(x))
elseif choice == 2
fprintf('cos(%.1f) is %.1f\n', x, cos(x))
elseif choice == 3
fprintf('tan(%.1f) is %.1f\n', x, tan(x))
elseif choice == 4
disp(Quit)
else
disp('Error!')
end

Solu'on using switch


% Prints either sin, cos, or tan of x
% uses the menu function to choose
x = input('Enter a value for x: ');
choice = menu('Choose a function, 'sin','cos','tan');
switch choice
case 1
fprintf('sin(%.1f) is %.1f\n', x, sin(x))
case 2
fprintf('cos(%.1f) is %.1f\n', x, cos(x))
case 3
fprintf('tan(%.1f) is %.1f\n', x, tan(x))
case 4
disp(Quit)
otherwise
disp('Error!')
end

The is func'ons
There are many is func'ons in MATLAB that
essen'ally ask a true/false ques'on, and
return logical 1 for true or 0 for false
isleDer : 1 for every character in a string is a leqer
of the alphabet or 0 if it is not
isempty : 1 if the variable argument is empty, or 0
if not
iskeyword : 1 if the string argument is a keyword,
or 0 if not in MATLAB

Vous aimerez peut-être aussi