Control statements in MATLAB
Decision making constructs
looping constructs
The decision making control statements permit to select and
execute specific section of code while skipping other sections of
code.
MATLAB has two decision making constructs : if construct and
switch construct.
Relational operators: symbols that are used to test relationship
between 2 variables or between variable and constant.
Operator operation
-------------------------------------------------- >> 3<4
== equal to
ans =
~= not equal to
1 True
> greater than
>> 3==4
>= greater than or equal to
ans =
< less than
False
<= less than or equal to 0
>>[30 40 50 60 70] > 40
--------------------------------------------------- ans =
00111
>> a=0;
>> b=sin(pi);
>> a==b
ans =
0
Two theoretically equal numbers can differ slightly due to round off
errors during computer calculations. This causes equality or
inequality test to fail.
Instead of comparing two numbers for exact equality, condition
can be set up to test if two numbers are nearly equal to each other
within some accuracy.
>> abs(a-b)<1.0e-14
ans =
1
Logical operators: symbols that are used to combine or negate the
expressions containing relational operators (conditions)
& AND
| OR
~ NOT
xor Exclusive OR
if statement
Syntax:
if e
statements
end
e is logical expression (condition)
which evaluates to either True or False
Ex: if x >= 0
y = sqrt(x)
end
if e
statements
else
statements
end
if e1
statements
elseif e2
statements
else
statements
end
Example revisted: Write a program to find area of a triangle if 3
sides are given.
%area of a triangle given 3 sides
x=input('Enter 3 sides of a triangle as elements of a row vector :');
%data validation
if (x(1)+x(2)<x(3)|x(2)+x(3)<x(1)|x(1)+x(3)<x(2))
disp('error in input data... try again');
else
s=sum(x)/2;%semiperimeter
area=sqrt(s*(s-x(1))*(s-x(2))*(s-x(3)));
fprintf('area = %f\n',area);
end
%area of a triangle given 3 sides
disp('Program to find area of a triangle when 3 sides are given');
a=input('Enter 1st side of a triangle :');
b=input('Enter 2nd side of a triangle :');
c=input('Enter 3rd side of a triangle :');
%data validation
if ~(a+b>c & a+c>b & b+c>a)
disp('error in input data... try again');
else
s=a+b+c/2;%semiperimeter
area=sqrt(s*(s-a)*(s-b)*(s-c));
fprintf('area = %f\n',area);
end
The syntax is:
scalar or string
switch expr
case v1
statement
...
case {v2,v3,...}
statement
...
otherwise
statement
...
end
The switch statement executes groups of statements based on
the value of a variable or expression. The keywords case and
otherwise delineate the groups. Only the first matching case is
executed. There must always be an end to match the switch.
MATLAB switch does not fall through. If the first case statement is true, the other case
statements do not execute. So, unlike in „C‟ break statements are not required.
The common use of switch is for writing menu driven program.
Example 1:
%program to display transmission line fault statistics
fault=input('Enter type of fault (LL/LG/LLG/LLL) in single quotes');
switch lower(fault)
case 'lg'
disp('probability of occurrence of LG fault is 85%');
case 'll'
disp('probability of occurrence of LL fault is 8%');
case 'llg'
disp('probability of occurrence of LLG fault is 5%');
case ‘lll’
disp('probability of occurrence of LLL fault is 2%');
otherwise
disp(‘invalid input’);
end
Generate a random integer number x between 1 to 10. If x = 1 to
3, then display the message Result = FF to the screen. If x = 4 to
10 then display message result =„Pass‟.
Round towards plus infinity
x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10}
switch x
case {1,2,3}
disp('Result = Fail');
otherwise
disp(„Result = Pass');
end
ceil: Round towards +infinity
round Round to nearest integer
floor Round towards minus infinity
fix Round towards zero
ceil Round towards plus infinity
While loop is used when the looping process terminates because a specified condition is
satisfied, and thus the number of passes is not known in advance.
while e
statements
end
Ex:
x = 5;
while x <25
disp (x)
x = 2*x-1;
end
The while loop repeats a group of statements an indefinite (not
infinite) number of times under control of a logical condition. A
matching end delineates the statements.
index
Never modify index within the body of
for variable = expression
the loop.
statements
end
The for loop repeats a group of statements a fixed, predetermined
number of times. A matching end delineates the statements.
Default increment of 1
for ii=1:10 for ii=[5 9 7] Explicitly written array
statements statements
end end
initial: increment:final Loop index can be
for ii=[1 2 3;4 5 6] a vector
for ii=1:2:10
statements statements
for ii=10:-1:1
end end
statements
end
disp('Program to compute factorial of a number');
n=input('Enter a number: ');
f=1;
for ii=1:n
f=f*ii;
end
fprintf('factorial of %u is %u\n',n,f);
disp('Program to compute factorial of a number');
n=input('Enter a number: ');
f=1;
ii=1;
while(ii<=n)
f=f*ii;
ii=ii+1;
end
fprintf('factorial of %u is %u\n',n,f);
Write the factorial program using functions.
function[f]=fact2(n)
f=1;
ii=1;
while(ii<=n)
f=f*ii;
ii=ii+1;
end
>> fact2(3)
ans =
6
Write a program to reverse digits of an integer number
%reversing digits of integer number
disp('Program to reverse digits of integer number');
fprintf('\n');
n=input('enter number to be reversed : ');
fprintf('\n');
nsave=n;rev_no=0;
while n>0
digit=rem(n,10);
rev_no=rev_no*10+digit;
n=fix(n/10);
end Rounding towards zero
fprintf('After reversing the digits, number %d becomes :%d\n',nsave,rev_no);
Program to reverse digits of integer number
enter number to be reversed : 1234
After reversing the digits, number 1234 becomes :4321
>>
Generate the following pattern
11111*
1111*1
111*11
11*111
1*1111
*11111
%Pattern generation program
for ii=1:6
for jj=1:6
if jj==7-ii
fprintf ('*');
else
fprintf('1');
end
end
fprintf('\n');
end
break and continue statements:
control the operation of while and for loops.
break statement terminates execution of loop and passes
control to the next statement after the end of loop.
continue statement terminates the current pass through the loop
and returns control to the beginning of the loop.
for ii=1:5 for ii=1:5
if ii==3 if ii==3
break; continue;
end
end
fprintf(„ii=%d \n‟,ii); fprintf(„ii=%d \n‟,ii);
end end
disp(„end of loop‟); disp(„end of loop‟);
try-catch construct
try
statement
...
statement
catch
statement
...
statement
end
Normally when program encounters error while running, the program aborts. The try-
catch constructs modifies this default behavior.
the statements between try and catch are executed until an error occurs.
If error occurs, instead of aborting, the statements between catch and end are
executed.
The code within catch and end can make use of the function lasterr
to access information about the error and act accordingly.
x = ones(4,2); x = ones(4,2);
y = 4*eye(3); % now wrong size y = 4*eye(3); % now wrong size
try try
z = x*y; z = x*y;
catch catch
z = nan; lasterr
disp('X and Y are not conformable.') end
end
z
ans =
Error using ==> mtimes
X and Y are not conformable.
Inner matrix dimensions must agree.
z=
NaN
Recursion is a kind of tricky and smart construct which allows a
function to call itself. or it is a type of programming technique
which involves the use of function that call itself one or more
times until a specified condition is met.
The Matlab programming language supports it, so a statement
within the function can call the same function during its
execution.
Two requirements to solve problem recursively:
1. to express the problem in recursive form
2. to include the stopping condition
Factorial of a number
Iterative definition Recursive definition
Factorial of a positive integer n is Factorial of a number is the product
the product of all integers from 1 of n and factorial of n-1
to n n! = n x (n-1)!
n! = 1 x 2 x …… n 1!=0!=1
Stopping condition Problem is expressed
in terms of previous
result which is
assumed to be known
function y = fact(n)
prod(1:n)
if n == 0
y=1
else
y = n * fact(n-1)
end
It is possible for the function to call itself forever and never
return an answer. That happens in the code above if we enter a
negative argument. How to avoid this?
Try-catch construct
built-in function (factorial(n)).
recursive function for computing y = 10^n
function y = ten_exp(n)
% This is a recursive function for computing y = 10^n.
% The program works only if n is a nonnegative integer.
% If n is negative, the algorithm won't stop.
if n == 0
y=1
else
n %<< this line is not needed but for inspection
y = 10 * ten_exp(n-1)
end
>> ten_exp(3)
n=
3
n=
2
n=
1
y=
1
y=
10
y=
100
y=
1000
ans =
1000
The advantages and disadvantages of the two approaches (recursion and iteration) are
not always obvious, and you should really take it on a case-by-case basis. When in
doubt: test it. But generally:
1. Recursion may be slower, and use greater resources, because of the extra function
calls.
2. Recursion may lead to simpler, shorter, easier-to-understand functions.
Towers of Hanoi
How do we transfer all disks from A to C, with the following limitations:
1) Only one disk at a time may be moved.
2) A larger disk may never lie on a smaller disk.
Subfunctions
• Allows more than one function to be within
the same M-file to modularize code.
• M-file must have the name of the first
(primary) function.
• Subfunctions can only be called from
within the same M-file.
• Each subfunction has its own workspace.
function [totalsum,average] = subfunc (input_vector)
% SUBFUNC Calculates cumulative total & average
Primary totalsum = sum(input_vector);
Function average = ourmean(input_vector); %Call to subfunction
function y = ourmean(x)
% (OURMEAN) Calculates average
[m,n] = size(x);
if m == 1
m = n;
Sub- end
Function y = sum(x)/m;
»[SUM, MEAN] = subfunc(rand(1,50))
>> [s a]=subfunc([1 2 3 4 5])
s=
15
a=
>> subfunc([1 2 3 4 5])
ans =
15
Types of errors in MATLAB programs
• Syntax errors
– Check spelling and punctuation
• Run-time errors
– Check input data
– Can remove “;” or add “disp” statements
• Logical errors
– Use shorter statements
– Check algorithm
– Check units