0% found this document useful (0 votes)
3 views5 pages

Matlab E4 Scripts Functions and Flow Control

The document outlines the objectives and overview of using M-file scripts and functions in MATLAB, emphasizing flow control structures like 'if-elseif-end', 'for loops', and 'while loops'. It details the differences between scripts and functions, including their syntax and usage, as well as providing examples for clarity. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

John Rhey Ibe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Matlab E4 Scripts Functions and Flow Control

The document outlines the objectives and overview of using M-file scripts and functions in MATLAB, emphasizing flow control structures like 'if-elseif-end', 'for loops', and 'while loops'. It details the differences between scripts and functions, including their syntax and usage, as well as providing examples for clarity. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

John Rhey Ibe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Exercise No.

4
SCRIPTS, FUNCTIONS AND FLOW CONTROL

NAME: DATE PERFORMED:


COURSE/ SECTION: DATE SUBMITTED:
GROUP NO.: INSTRUCTOR:

I. OBJECTIVES:
1. To introduce how to write M-file scripts, create MATLAB functions
2. To review MATLAB flow control like ‘if-elseif-end’, ‘for loops’ and ‘while loops’.

II. OVERVIEW:
MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain code in the
MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB
function or command.

There are two kinds of M-files:


 Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.
MATLAB provides a full programming language that enables you to write a series of MATLAB statements into a file and
then execute them with a single command. You write your program in an ordinary text file, giving the file a name of
‘filename.m’. The term you use for ‘filename’ becomes the new command that MATLAB associates with the program. The
file extension of .m makes this a MATLAB M-file.
 Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.If
you're a new MATLAB programmer, just create the M-files that you want to try out in the current directory. As you develop
more of your own M-files, you will want to organize them into other directories and personal toolboxes that you can add to
your MATLAB search path. If you duplicate function names, MATLAB executes the one that occurs first in the search
path.

Scripts:
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the
workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that
they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using
functions like plot. For example, create a file called ‘myprogram.m’ that contains these MATLAB commands:

% Create random numbers and plot these numbers


clc
clear
r = rand(1,50)
plot(r)

Typing the statement ‘myprogram’ at command prompt causes MATLAB to execute the commands, creating fifty random numbers
and plots the result in a new window. After execution of the file is complete, the variable ‘r’ remains in the workspace.

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. Functions operate on variables within their own workspace, separate from the workspace you access at the
MATLAB command prompt. An example is provided below:

function f = fact(n) Function definition line


% Compute a factorial value. H1 line
% FACT(N) returns the factorial of N, Help text
% usually denoted by N!
% Put simply, FACT(N) is PROD(1:N). Comment
f = prod(1:n); Function body

M-File Element Description


Function definition line Defines the function name, and the number order of input and output arguments.
(functions only)
H1 line A one line summary description of the program, displayed when you request help
on an entire directory, or when you use ‘lookfor’.

Help text A more detailed description of the program, displayed together with the H1 line
when you request help on a specific function
Function or script body Program code that performs the actual computations and assigns values to any
output arguments.

Comments Text in the body of the program that explains the internal workings of the
program.

The first line of a function M-file starts with the keyword ‘function’. It gives the function name and order of arguments. In this case,
there is one input arguments and one output argument. 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 ‘help fact’. 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.

The variable n & f introduced in the body of the function as well as the variables on the first line are all local to the function; they are
separate from any variables in the MATLAB workspace. This example illustrates one aspect of MATLAB functions that is not
ordinarily found in other programming languages—a variable number of arguments. Many M-files work this way. If no output
argument is supplied, the result is stored in ans. If the second input argument is not supplied, the function computes a default value.

Flow Control:
Conditional Control – if, else, switch
This section covers those MATLAB functions that provide conditional program control. if, else, and elseif. The if statement evaluates
a logical expression and executes a group of statements when the expression is true. 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.
The groups of statements are delineated by the four keywords—no braces or brackets are involved as given below.

if <condition>
<statements>;
elseif <condition>
<statements>;
else
<statements>;
end

It is important to understand how relational operators and if statements work with matrices. When you want to check for equality
between two variables, you might use

if A == B, ...

This is valid MATLAB code, and does what you expect when A and B are scalars. But when A
and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's
showing element-by-element equality. (In fact, if A and B are not the same size, then A == B is an error.)

>>A = magic(4);
>>B = A;
>>B(1,1) = 0;
>>A == B
ans =
0 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

The proper way to check for equality between two variables is to use the isequal function:

if isequal(A, B), ...

isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix, as the expression to be evaluated by
the if function.

Using the A and B matrices from above, you get

>>isequal(A, B)
ans =
0

Here is another example to emphasize this point. If A and B are scalars, the following program will never reach the "unexpected
situation". But for most pairs of matrices, including our magic

if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end

squares with interchanged columns, none of the matrix conditions A > B, A < B, or A == B is true for all elements and so the else
clause is executed:

Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including ‘isequal’,
‘isempty’, ‘all’, ‘any’.

Switch and Case:


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. The syntax is as follows

switch <condition or expression>


case <condition>
<statements>;

case <condition>

otherwise
<statements>;
end

There must always be an end to match the switch. An example is shown below.

n=5
switch rem(n,2) % to find remainder of any number ‘n’
case 0
disp(‘Even Number’) % if remainder is zero
case 1
disp(‘Odd Number’) % if remainder is one
end

Unlike the C language switch statement, MATLAB switch does not fall through. If the first case statement is true, the other case
statements do not execute. So, break statements are not required.

For, while, break and continue:


This section covers those MATLAB functions that provide control over program loops.

for:
The ‘for’ loop, is used to repeat a group of statements for a fixed, predetermined number of times. A matching ‘end’ delineates the
statements. The syntax is as follows:

for <index> = <starting number>:<step or increment>:<ending number>


<statements>;
end

for n = 1:4
r(n) = n*n; % square of a number
end
r

The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested:

for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end

while:
The ‘while’ loop, repeats a group of statements indefinite number of times under control of a logical condition. So a while loop
executes atleast once before it checks the condition to stop the execution of statements. A matching ‘end’ delineates the
statements. The syntax of the ‘while’ loop is as follows:

while <condition>
<statements>;
end

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial:

a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x

The result is a root of the polynomial x3 - 2x - 5, namely x = 2.0945. The cautions involving matrix comparisons that are discussed in
the section on the if statement also apply to the while statement.

break:
The break statement lets you exit early from a ‘for’ loop or ‘while’ loop. In nested loops, break exits from the innermost loop only.
Above is an improvement on the example from the previous section. Why is this use of break a good idea?

a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end

continue:
The continue statement passes control to the next iteration of the for loop or while loop in which it appears, skipping any remaining
statements in the body of the loop. The same holds true for continue statements in nested loops. That is, execution continues at the
beginning of the loop in which the continue statement was encountered.
IV. Exercises:

Note: submit the exercises (m-files and results) in the next lab

1. MATLAB M-file Script


Use MATLAB to generate the first 100 terms in the sequence a(n) define recursively by

with p=2.9 and a(1) = 0.5.

2. MATLAB M-file Function


Consider the following equation

a) Write a MATLAB M-file function to obtain numerical values of y(t). Your function must take y(0), ζ, ωn, t and θ as function inputs
and y(t) as output argument.
b) Obtain the plot for y(t) for 0<t<10 with an increment of 0.1, by considering the following two cases

Case 1: y(0)=0.15 m, ωn = √2 rad/sec, ζ = 3/(2√2) and θ = 0;


Case 2: y(0)=0.15 m, ωn = √2 rad/sec, ζ = 1/(2√2) and θ = 0;

3. MATLAB Flow Control


Use ‘for’ or ‘while’ loop to convert degrees Fahrenheit (Tf) to degrees Celsius using the following equation

Use any starting temperature, increment and ending temperature (example: starting temperature=0, increment=10, ending
temperature = 200).

V. Generalization:
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________

You might also like