0% found this document useful (0 votes)
5 views

Selective Structures

The document discusses different selection statements in Matlab: 1) if - executes or skips a block of statements depending on a condition 2) if else - executes one of two blocks depending on if a condition is true or false 3) if elseif else - can execute one of many blocks depending on which condition is true Examples are provided to illustrate the use of if, if else, and if elseif else statements.

Uploaded by

nazhirah musa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Selective Structures

The document discusses different selection statements in Matlab: 1) if - executes or skips a block of statements depending on a condition 2) if else - executes one of two blocks depending on if a condition is true or false 3) if elseif else - can execute one of many blocks depending on which condition is true Examples are provided to illustrate the use of if, if else, and if elseif else statements.

Uploaded by

nazhirah musa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Topic 10

Selective Structures
if
if else
if elseif else
switch

1
Recapitulation

• PDC
• Algorithm & Flow chart, pseudo code
• Transfer of control/ control structure
• Conditions, Relational & Logical operators,
order of precedence
• or ,and, not, xor, find functions
Introduction

Matlab has two type of selection statements.


• if
• switch

There are 3 forms of if statement;


1)if Skip or execute a block of statements

2)if else Execute only one of two block of statements

3)if elseif else Executes only one


of many blocks of statements

3
if
if statements flowchart

se
Condition?

el
if
True False

se
Steps to process if

el
True Steps to process
Condition is True Condition 1
if condition 1 is True

if
False

True Steps to process


Condition 2
if condition 2 is True
False
se

True Steps to process


el

Condition? Condition 3
if condition 3 is True
if

True False False

Steps to process if Steps to process if Steps to process


Condition is True Condition is False if all above
conditions False

4
if statement
Execute or skip a block of statements

flowchart
format
if condition Condition?

Actions process executed if


the condition is true True False
end process if
Condition is True

5
if statement - Example 1
Enter a number to determine its square root. If the user enters a negative
number it use the absolute value.
num=input('Enter a number: ');
if num < 0
disp('We''ll use absolute value') Executed if the
num=abs(num); condition if TRUE
end
fprintf('The sq.root of %.f is %.2f\n',num,sqrt(num))
Without the IF statement,
what would be the result
when num is –ve?

>> ifexample1
With the IF statement
what if the input is a ; Enter a number: -45
• +ve number We'll use absolute value
• -ve number The sq.root of 45 is 6.71

6
if statement - Example 2
Calculate the cross-section area of a circular tube. If the user enter inner radius
larger than the outer radius, the program automatically interchange the values.
clear;clc
irad=input(‘Tube inner radius : ');
orad=input(‘Tube outer radius : ');
if orad < irad
t=orad;
orad=irad; Executed if the
condition isTRUE t?
irad=t;
end
xarea=pi*(orad^2-irad^2);
fprintf('\nInside radius %.2f\nOutside radius
%.2f\n',irad,orad)
fprintf('x section area = %.3f\n',xarea)
Inside radius 1.00 without the IF statement,
Outside radius 2.00 what would be the result
x section area = 9.425 when orad < irad ? 7
Try This !
Write Matlab script file to determine
the value of y at any given x value.
Use if statement.

clear;clc
x=input ('Enter x value; ');
y=x;
if x>20
y=20;
end
fprintf ('When x = %.1f , y = %.1f\n',x,y)
This can be written in many ways
Try This !
Write Matlab script file to determine
support reactions of the beam shown.
Use if statement to check that
0 < a < l.

a
clear;clc
p=input('P = ');
l=input('l = ');
a=input('a = ');
rb=p*a/l;ra=p-rb;
fprintf('Ra = %.2f and Rb = %.2f\n',ra,rb);
if a<0 || a>l
clc
disp('Incorrect input')
end
Try This !

b
clear;clc
p=input('P = ');
l=input('l = ');
a=input('a = ');
if a<0 || a>l
disp('Incorrect input')
break
end
rb=p*a/l;ra=p-rb;
fprintf('Ra = %.2f and Rb = %.2f\n',ra,rb);
if else statement

Execute only one of


2 blocks of statements

11
if else statement

flowchart
format
if condition
Actions Condition?
executed if the
Action 1 condition is
TRUE True False
else Action1 if Action 2 if
Actions Condition is Condition is
Action 2 executed if the
condition is
True False
FALSE
end

12
if else statement - Example 1
Write a program asking the user to enter two integer numbers,
then create a vector in an ascending order.
a=input('Please enter a number: ');
b=input('Please enter a another number: ');
if a < b
vec=a:b Which statement is executed when:
else a) a=6, b=4
vec=b:a b) a=6, b=10
end

>> ifelseexample1

Please enter a number: 6


Please enter a another number: 4
vec =
4 5 6

What if a=b? 13
Try This !
Write Matlab script file to determine the
value of y at any given x value.
Use if-else statement.

clear;clc
x=input ('Enter x value; ');
if x<20
y=x;
else
y=20;
end
fprintf ('When x = %.1f , y = %.1f\n',x,y)

This can be written in many ways


if else statement - Example 2
Write a program to determine the support reactions of a simply supported beam
carrying a point load. Validate that the load distance is between 0 and span length..

Algorithm - flowchart?

15
if else statement - Example 2
l=input('Beam span = ');
p=input('Load = ');
a=input('Load dist. = ');
if a<0 || a>l
fprintf('load out of range\n')
else
rb=p*a/l;ra=p-rb;
fprintf('Ra = %.2f\t\tRb = %.2f\n',ra,rb)
end

>> ifelseexample2
Beam span = 5
Load = 12
Load dist. = 3
Ra = 4.80 Rb = 7.20

What if d = 6 , l =5 ?

Modify the program to include validation l > 0 16


Try This !
Write a Matlab script to calculate the bending moment at any point, x
specified by the user for the beam below.
Algorithm - flowchart?
x P

% data input
RA a % calc reactions
RB
if x <= a
Bending Moment Diagram Mx = RA * x executed if x<=a
else
Mx = RA*x - P*(x-a) executed
if x>a
Mx = RA * x End
Mx= RA*x - P*(x-a) % display result

Add bending moment diagram and shear force diagram to the program. 17
Try This !
Write a Matlab script to determine and display the maximum bending
moment and its location of a simply supported beam carrying two point
loads.
Algorithm?

What if Mc = Mb ?

Add bending moment and shear force diagram to the program 18


if-elseif-else statement

Execute only one of


many blocks of statements

19
if-elseif-else statement
format flowchart
if condition1
Actions executed if
Action 1 the condition1 is true True Action 1 executed
elseif condition2 Condition 1
if condition 1 True
Actions executed if
Action 2 the condition2 is true False

elseif condition3 Condition 2


True
Action 2executed
Action 3 Actions executed if if condition 2 True
the condition3 is true False
else
True
Actions executed all
Action 4 the above condition s
Condition 3 Action 3 executed
if condition 3 True
end are false False

Action 4 executed
if ALL the above
conditions are False

Note:
• No condition after else
• else is optional
• the conditions may be unrelated 20
if-elseif-else statement – Example 1
elseifexample1.m
sem=input('No. semester: '); >> elseifexample1
cpa=input('CPA: '); No. semester: 4
gpa=input('GPA: '); CPA: 3.4
nat=input('Malaysian (y/n): ','s');
nat=lower(nat); GPA: 3.6
Malaysian (y/n): y
if cpa>3.5 Masih ada masa
disp('Good, still room for improvement')
elseif gpa>3.75
What if the order of the
disp('Excellent, keep it up')
conditions is changed?
elseif sem<6
disp('Masih ada masa')
elseif nat=='y' What will the be output if the;
disp('Malaysia Boleh') a) cpa=3.5,gpa 3.8, sem 5, nat y,
else b) cpa=3.6,gpa 3.5, sem 7, nat n,
disp('Good Luck') c) cpa=3.5,gpa 3.0, sem 5, nat n,
end
21
Try This !
Write a Matlab script to determine and display the maximum bending
moment and its location of a simply supported beam carrying two point
loads. There are 3 output possibilities a) Mc>Md, b) Mc<Md, c) Mc=Md.

22
AClassSSB2PtLoad - with DV

Try This !
Write a Matlab script to calculate the bending moment at any point specified,
x by the user for the beam below.

x % data input …
% calc reactions …
if x <= d1
Mx = RA * x executed if x<=a
elseif x<=d2 executed if
Bending Moment Diagram
x>d1
Mx = RA*x – P1*(x-d1) and
else x<=d2

Mx = RB*(l-x) executed if none of the


above conditions is true
end
Algorithm - flowchart?
% display result …

23
Nested if

24
Nested if
A branch of one selective structure (if statement)
includes another complete selective structure inside it.
The inner most if must always end before the outer if.

True False
Engineering?

Steps P
Steps A

Maths=A? Sports?
True False
True False
Community
Games Extra Class Gymnasium
service

Steps D Steps T

25
Nested if - Example
Write a script to determine the value of sd.
Use nested if. The user has to input curve
(A or B), and the cs value.
Check the programming using the following
values,

Curve ChrStr StdDev


a) A 15 ?
b) B 15 ?
c) B 20 ?
d) A 30 ?

Algorithm?

26 26
Nested if – Example (cont’d)
nestedifexample1.m
curve=input('Please enter curve (a or b): ','s');
cs=input('Please enter cs: ');
if curve=='a'
>> nestedifexample1
if cs<20
sd=0.4*cs; Please enter curve (a or b): b
else Please enter cs: 12
sd=8; standard devition is 2.4
end
else
if cs<20
sd=0.2*cs;
else
sd=4;
end
end
fprintf('standard devition is %.1f\n',sd)

27
Nested if – Example
The nested if in the previous example can be avoided by using
logical operator &&.
nestedifexample1mod.m
curve=input('Please enter curve (a or b): ','s');
cs=input('Please enter cs: ');
if curve=='a' & cs<20
sd=0.4*cs; >> nestedifexample1mod
elseif curve=='a' & cs>=20
Please enter curve(a or b): b
sd=8;
elseif curve=='b' & cs<20 Please enter cs: 10
sd=0.2*cs; standard devition is 2.0
elseif curve=='b' & cs>=20
sd=4;
end
fprintf('standard devition is %.1f\n',sd)

Which do you prefer,


the nested if or this one? 28
Try This !
Write a Matlab script to calculate the bending moment at any point, x
specified by the user for the beam below. Validate the input that x and a are
within the beam span. ie. 0 = x ≤ l, 0 = a ≤ l.

P Algorithm - flowchart?
x

a If the distance input is incorrect


RA RB Warn the user and terminate program
Else
Bending Moment Diagram Process
end

Mx = RA * x Mx = RA*x - P*(x-a)

29
start

if
ed Input
l,a,x,p
st
Ne

Y
Cond. 1
Condition 1
x<0 or x>l or N
a<0 or a>l Calc. Rb, Ra

Condition 2 N Y
x≥a Cond. 2

Mx=Ra.x Mx=Rb(l-x)

Disp.
result

end
l=input('beam span = ');
d=input('load dist. = ');
p=input('load = ');
x=input('Point x = ');
if x<0|x>l|d<0|d>l
disp('PLEASE CHECK INPUT DISTANCE')
else
rb=p*d/l;ra=p-rb;
if x<=d
mx=ra*x;
else
mx=rb*(l-x);
end
md=ra*d;
fprintf('\n\nRa = %.2f\t Rb = %.2f\n',ra,rb)
fprintf('BM at x = %.1f is %.2f\n',x,mx)
end
switch statement

Another form of selective structure.


switch statement can often be used in place of
nested if-else or if-elseif statements.

32
switch statement
format
switch switch_expression
case caseexpr1 Single value
Actions-1
case caseexpr2
Actions-2
case {caseexpr4,caseexpr5} List of values
Actions-3
otherwise
Action-N
end

• Switch expression can be numbers or string.


• The switch tests each case until one of the cases is true. If
the value of the switch expression does not match any of the
case expression, the action after the otherwise is executed. 33
switch statement
flowchart
• Can avoid complex if
Evaluate switch expression
statements by using case
Steps to process if
True statement
Compare case 1 Switch_expr=case 1
Is True
False • Use case structure when
Steps to process if
Compare case 2
True
Switch_expr = case 2 the decision variable has
is True more than two or three
False possible values
True Steps to process if
Compare case 3 Switch_expr = case 3
is True • switch is an efficient
False
selective structure that
Steps to process simplifies choosing from
if all above
cases is False several actions

34
switch statement - Example
switchexample1.m
qmark=input('Please enter quiz mark: ');
switch qmark
case {9 10}
grade='A'; >> switchexample1
case 8 Please enter quiz mark: 6
grade='B'; quiz grade is D
case 7
>> switchexample1
grade='C';
case 6 Please enter quiz mark: 9
grade='D'; quiz grade is A
otherwise
grade='E';
end
fprintf('quiz garde is %c\n',grade)

What if the input qmark is <0 or >10?


What if the input is not an integer between 0 and 10? 35
Problem Examples

36
Problem Example 1
A simply supported beam is partially loaded with a uniformly
distributed loaded as shown. Write a program to calculate the bending
moment and shear force at any point specified by the user.

Algorithm?

37
Problem Example 1 – cont’d
ifelseif_ssbudlbms
f
q=input('Enter load intensity, q: ');
d1=input('Enter load start dist., d1: ');
d2=input('Enter load end dist., d2: ');
l=input('Enter beam span., l: ');
x=input('Enter bm required dist., x: ');
disp(‘ ‘)

qlen=d2-d1;qtot=qlen*q;
rb=(qtot*(d1+d2)/2)/l;
ra=qtot-rb;

38
Problem Example 1 – cont’d
if x<=d1
bmx=ra*x;
vx=ra;
elseif x<=d2
bmx=ra*x-q*(x-d1)^2/2;
vx=ra-q*(x-d1);
else
bm=rb*(l-x);
vx=ra-qtot;
end

fprintf('Reaction at A is %.2f & at B is


%.2f\n',ra,rb)
fprintf('At x = %.1f the BM = %.2f and SF =%2.f\n',...
x,bmx,vx)

39
Problem Example 1 – cont’d

>> ifelseif_ssbudlbmsf

Enter load intensity, q: 15


Enter load start dist., d1: 2
Enter load end dist., d2: 6
Enter beam span., l: 7
Enter bm required dist., x: 5

Reaction at A is 25.71 & at B is 34.29


At x = 5.0 the BM = 61.07 and SF =-19

Add data validation.


40
Problem Example 2
Determine the magnitude and direction (angle
between 0 and 360 degree) of the resultant
force for the force system shown.

Algorithm?

42
Problem Example 2 - cont’d
f=input('Enter a row vector of 4 forces: ');
a=input('Enter a row vector of the 4 angles: ');
fx=f.*cosd(a);
fy=f.*sind(a);
fxtot=sum(fx);
fytot=sum(fy);
fr=sqrt(fxtot.^2+fytot.^2);
fra=atand(fytot/fxtot);

if fxtot>0 && fytot>0


fra=fra;
elseif fxtot<0 && fytot>0
fra=180+fra;
elseif fxtot<0 && fytot<0
fra=180+fra;
else
fra=360+fra;
end
43
Problem Example 2 - cont’d
mat=[1:4;f;a];
disp(' ')
disp ('Resultant of 4 Concurrent Forces')
disp(' ')
disp(' Force Angle')
fprintf('%i %.1f %.1f\n',mat)

fprintf('\nResultant force = %.1f and\n',fr)


fprintf('angle is %.1f degrees\n',fra)

44
Problem Example 2 - cont’d
Enter a row vector of 4 forces: [70 100 75 80]
Enter a row vector of the 4 angles: [30 100 200 330]

Resultant of 4 Concurrent Forces

Force Angle
1 70.0 30.0
2 100.0 100.0
3 75.0 200.0
4 80.0 330.0

Resultant force = 79.8 and


angle is 58.2 degrees
>>
More practice see Problem B2

Thank You

46

You might also like