MATLAB-5
MATLAB-5
Programming In MATLAB
BSCpE 4
Flow Control
2
Flow Control
• MATLAB has several flow control constructs:
– if
– For
– while
– Continue
– Break
– try – catch
– return
3
IF-Statement
• The optional elseif and else keywords provide for the execution of alternate
groups of statements.
• An end keyword, which matches the if, terminates the last group of
statements.
4
IF-Statement
• The optional elseif and else keywords provide for the execution of alternate
groups of statements.
• An end keyword, which matches the if, terminates the last group of
statements.
5
IF-Statement
• For Example write a program that accepts a number and displays Good if
number is greater than 4 and displays Bad when number is less than 4 and
displays Exactly when number is equal to 4.
for I = 1:N,
for J = 1:N,
end
8
Nested For-Statement
• We can also insert another for statement inside existing for
statement.
for I = 1:N,
for J = 1:N,
A(I,J) = 1/(I+J-1);
end
end
9
For-Statement
• Write a MATLAB code to print table of entered number.
for I = 1:n,
end
10
Activity #2
1. Write Down the MATLAB program to print first 20 odd
numbers.
4 1 1 1 1
f (t ) = (cos t − cos 3t + cos 5t − cos 7t + cos 9t )
3 5 7 9
11
Switch and Case
• The switch statement executes groups of statements based on the
value of a variable or expression.
14
While-Statement
• The while loop repeats a group of statements an indefinite
number of times under control of a logical condition.
• A matching end delineates the statements.
while a<30
end
15
Exercise#4 (contd… )
3. Now modify this program in such a way that computer also
indicates number of attempts to guess the number .
16
Functions
17
Functions
• Functions are M-files that can accept input arguments and return
output arguments.
• The names of the M-file and of the function should be the same.
18
Functions
• The first line of a function M-file starts with the keyword function. It
gives the function name and order of arguments.
• The next several lines, up to the first blank or executable line, are
comment lines that provide the help text. These lines are printed when
you type
• The first line of the help text is the H1 line, which MATLAB displays
when you use the lookfor command or request help on a directory.
• The rest of the file is the executable MATLAB code defining the
function.
19
Functions
• Lets create a function that accepts one numeric value and notify that the
number is even or odd.
function evenodd(n)
if mod(n,2)==0
elseif mod(n,2)==1
end
20
Functions
function evenodd(n)
% Example evenodd(7)
% Matlab Returns
if mod(n,2)==0
elseif mod(n,2)==1
22
Activity #6
1. Develop a MATLAB function with one input argument
trig(n) that produce sine and cos vlaues as two output
arguments .
24
Activity #6 (contd….)
3. Develop a MATLAB function that accepts a symbolic
expression of one variable and returns its integral and
derivative.
25