Programming with MATLAB – Control Structures
COM 103 ICT Applications in Food Industry (1+2)
Practical Schedule 7
Dr. S. Sridevy, Ph.D.
Assistant Professor (Computer Science)
Dept. of Physical Sciences & IT
AEC&RI, TNAU, Coimbatore – 3.
24 June 2020
if Structure
if expression
statements
elseif expression
statements
else
statements
end
S. Sridevy
24 June 2020
Example 1
yourNumber = input('Enter a number: ');
if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
What will the two disp statements produce?
a = 5; b = 6; c = 3;
if a > 3 && c < 7
result = a + b*c;
elseif a > 1 && b == 3
result = a*c;
elseif b == 5 || c < 5
result = b-15;
end
disp(‘result = ‘);disp(result)
S. Sridevy
24 June 2020
a = 5; b = 6; c = 3;
if a > 3 && c < 7
result = a + b*c;
end
if a > 1 && b == 3
result = a*c;
end
if b == 5 || c < 5
result = b-15;
end
disp(‘result = ‘);disp(result)
S. Sridevy
24 June 2020
Switch statement
switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end
S. Sridevy
24 June 2020
switch angle
case 45
disp(‘Northeast’)
case 135
disp(‘Southeast’)
case 225
disp(‘Southwest’)
case 315
disp(‘Northwest’)
otherwise
disp(‘Direction Unknown’)
end
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
grade = 'B';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Well done\n' );
case 'D'
fprintf('You passed\n' );
case 'F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end
When you run the file, it displays:
Well done
Your grade is B
S. Sridevy
24 June 2020
S. Sridevy
24 June 2020
Loop Structure
S. Sridevy
24 June 2020
for Loop
for loop variable = m:s:n
statements
end
S. Sridevy
24 June 2020
Develop the script
S. Sridevy
24 June 2020
Script
total = 0;
for k = 1:15
total = 5*k^2 - 2*k + total;
end
disp (‘The sum for 15 terms is:’)
disp (total)
S. Sridevy
24 June 2020
while Loop
while logical expression
statements
end
S. Sridevy
24 June 2020
while Loop (Contd.)
S. Sridevy
24 June 2020
while Loop (Contd.)
1. The loop variable must have a value before the while statement is executed.
2. The loop variable must be changed somehow by the statements.
S. Sridevy
24 June 2020
while Loop (Contd.)
S. Sridevy
24 June 2020
Script
total = 0;
k = 0;
while total < 5
k = k + 1;
total = 1+k + total;
end
disp(‘The number of terms is:’)
disp(k)
disp(‘The sum is:’)
disp(total)
S. Sridevy
24 June 2020
Thank You!