Loops and Conditional Statements Dr.Abbas
Lab 4
For loops
To run a command more than once as an index varies, you may use a for loop.
% display of numbers for i = 1:9
disp(i) End
% 6!
fact = 1;
for i = 2:6 fact = fact * i;
end
Ex 1:
Write m-file to compute the factorial of any integers !
The Solution :
N= input('Enter the number to calculate the factorial: ');
fact=1;
for i=2:N
fact=fact*i;
end
disp(fact)
% Calculate the Square of numbers 1 to 5 for i = 1:5
disp([int2str(i) ' squared equals ' int2str(i^2)]) end
Note : INT2STR used to convert integer to string
.
Summing Series
total = 0;
for n = 1:6
total = total + 2ˆn;
end
% function
function [out] = f(in1)
out = in1 * sin(in1 *pi/4);
% loop
maxN = input('Enter the value of N : ');
I(1) = f(1);
for N=2:maxN
I(N) = I(N-1) + f(N);
end
disp('Values of I_N') disp(I)
>>
maxN = input('Enter the value of N : ')
;
for N=2:maxN
X= N * sin (N *pi \ 4) end
disp('Values of I_N')
disp(X)
EXERCISE :
Calculate the summations
While loop:
while (condition) commands...
end
Examples
x=1 •
;
while x<=100 • disp(x) •
;
x=x+1 •
;
end •
EX :
Write out the values of x2 for all positive integer values x such that x3 < 2000.
x = 1;
while x^3 < 2000 disp(x^2)
x = x+1;
end
n = 10 ;
while n > 0
disp('Hello World') n = n - 1
;
end
IF Statement
if (expression) commands ...
elseif (expression) commands ...
else
commands ...
end
a=50
;
if a<10 b=a/2
;
else b=a/5
;
end
if x >= 0 & x <= 1 f = x;
elseif x > 1 & x <= 2 f = 2-x;
else f = 0;
end
Conditional Statements
if logical_expression1 • statements1 •
elseif logical_expression2 • statements2 •
else •
statements3 •
end •
if 2>4 • a=5 •
elseif 2<1 • a=6 •
else • a=10 •
end •
The MATLAB Command switch
clc;
n=input('Please input the figure:','s') switch n
case ('triangle') n=3;
sum=(n-3).*(180) case ('square') n=4;
sum=(n-3).*(180) case('pentagon') n=5;
sum=(n-3).*(180) case ('hexagon') n=6;
sum=(n-3).*(180) end
color = 'rose
;'
switch lower(color)
case {'red', 'light red', 'rose'}
disp('color is red')
case 'blue '
disp('color is blue')
case 'white '
disp('color is white')
otherwise
x=input('Enter the value of N : ') u=input('Enter the value of s : ')
switch u
case {'in','inch'} % multiple matches
y = 2.54*x; % converts to centimeters
disp ([num2str(x) ' ' u ' converted to cm is :' num2str(y)])
% disp is used to print pretty in the command window
% in the above a string vector is being printed
case {'m','meter'}
y = x*100; % converts to centimeters
disp ([num2str(x) ' ' u ' converted to cm is :' num2str(y)])
case { 'millimeter','mm'}
y = x/10
;
disp ([num2str(x) ' ' u ' converted to cm is :' num2str(y)])
case {'cm','centimeter'}
y = x
;
disp ([num2str(x) ' ' u ' converted to cm is :' num2str(y)])
otherwise
disp (['unknown units:' units])
 
 20
1
) sin(
i
i
A 
HW.3