MATLAB Scripts &
Functions
ELE-COA-411
By: A.J.R Ndalama
andalama@[Link]
2024
Scripts
• Scripts are the simplest kind of
code file because they have no
input or output arguments.
• They are useful for automating
series of MATLAB® commands.
2
A.J.R NDALAMA - 2023
Scripts
• You can create a new script in the following ways:
• Highlight commands from the Command History, right-click, and
select Create Script.
• On the Home tab, click the New Script button.
• Use the edit function.
For example, edit new_file_name creates (if the file does
not exist) and opens the file new_file_name. If
new_file_name is unspecified, MATLAB opens a new file called
Untitled.
• After you create a script, you can add code to the script and save it.
3
A.J.R NDALAMA - 2023
Scripts
MATLAB scripts:
• Do not accept input arguments or return output arguments
• Operate on data in the workspace
• Useful for automating a series of steps you need to perform
many times
4
A.J.R NDALAMA - 2023
Scripts – Syntax Highlighting
• To help you identify MATLAB® elements, some entries appear in
different colors in the Command Window, the Editor, and the
Live Editor.
• This color display is known as syntax highlighting. By default:
• Keywords are blue.
• Character vectors and strings are purple.
• Unterminated character vectors are maroon.
• Comments are green.
5
A.J.R NDALAMA - 2023
Scripts
MATLAB scripts:
• Like any other m-file are saved with an extension .m and
are executed by:
• clicking run or
• by typing the name of the m-file on the command
window without .m
• Work on global variables, i.e. variables currently available in
the work space.
• May contain a number of commands, including those that call
in-built functions
6
A.J.R NDALAMA - 2023
% An example of a Script M-file
% A script m-file that calculates wire
resistance
%
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
clc % Clear the command window
p = input('Enter Resistivity of wire: ');
r = input('Enter wire radius: '); Input
l = input('Enter wire length: ');
cross_Area = pi*r*r; % calculates cross section
area Program
R = (p*l)/cross_Area; % calculates resistance
disp('*********Results**********')
fprintf(['\n The resistance of the wire ' ... Output
'is: %.2f ohms \n'], R) 7
A.J.R NDALAMA - 2023
Scripts
• Never name a script m-file the same name of a variable it computes.
▪ E.g. naming a script as temp_1.m that computes a variable
temp_1. MATLAB will not execute the script because it will be
overwritten by the variable temp_1.
• The name of a script file must begin with a letter. The rest of characters
may include digits and underscore characters e.g.
action_potentialProject.m , bbm4_assign1.m,
Imissu.m
• Be sure that your script name is not for an inbuilt MATLAB function. Use
exist('name')to check.
8
A.J.R NDALAMA - 2023
User Functions
• To calculate the resistance of another wire using the same script, you
could update the values of p, l and r in the script and rerun it.
• However, instead of manually updating the script each time, you can
make your code more flexible by converting it to a function.
• Function declaration includes the
function keyword, the names of
input and output arguments, and
the name of the function.
• A function begins with a function
definition line 9
A.J.R NDALAMA - 2023
function R = wire_resistance(p,r,l)
% An example of a Function M-file
% A function m-file that calculates wire resistance
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cross_Area = pi*r*r; % calculates cross section area
R = (p*l)/cross_Area; % calculates resistance
end
10
A.J.R NDALAMA - 2023
User Functions
Line 1: The function definition line
Line 2: help line (H1), appears when you
use lookfor command
Line 3: Additional help lines, appear
together with H1 when using
help wire_resistance
Line 5-15: body of the function
11
A.J.R NDALAMA - 2023
User Functions
Exercise: Modify your wire_resistance function so that
instead of prompting for wire resisitivity, radius and
length inputs from the user, the function should accept input
arguments (wire resisitivity, radius and length) and
return cross_Area and resisitivity as output arguments.
12
A.J.R NDALAMA - 2023
function [R, csa] = wire_resistance(p, r, l)
csa = pi*r*r; % calculates cross section
area
R = (p*l)/csa; % calculates resistance
end
In the command window pass the following values 2.6,0.5,150 to the
wire_resistance function and store the results in resistance
and cross_Area.
>> [resistivity, cross_Area] = wire_resistance(2.6,0.5,150)
Resistance =
496.5634
cross_Area =
0.7854 13
A.J.R NDALAMA - 2023
function [R, csa] = wire_resistance(p, r, l)
csa = pi*r*r; % calculates cross section area
R = (p*l)/csa; % calculates resistance
end
Note: The variables p, r and l are local to the function
wire_resistance so unless you pass their values by
naming them p, r and l, their values will not be available
in the workspace outside the function.
14
A.J.R NDALAMA - 2023
• Only the order of the arguments is important, not the names of
the arguments:
>> p = 2.6;
>> r = 0.5;
>> l = 150;
>> [res, csa] = wire_resistance(p,r,l)
res =
496.5634
csa =
0.7854
• The second line is equivalent to :
>> [res, csa] = wire_resistance(2.6,0.5,150)
res =
496.5634
csa =
0.7854 15
A.J.R NDALAMA - 2023
Programming: Decision
Branching
• MATLAB has its own syntax for control-flow statements which are:
o for-loops
o while- loops
o if-elseif-else branching
• In addition, it provides other commands: break, switch-
case-otherwise, error and return to control the
execution of scripts and functions.
16
A.J.R NDALAMA - 2023
Programming: If-elseif-else
• The body of an if block executes only if the condition is true.
• You can check for equality by using the == operator.
if x == 0.5
y = 3
end A.J.R NDALAMA - 2023
17
Programming: If-elseif-else
• To execute some other code if the condition is not met,
you can use the else keyword.
x = rand();
if x > 0.5
y = 3
else
y = 4
end
18
A.J.R NDALAMA - 2023
Programming: If-elseif-else
• To add more conditions to your if block, use the elseif
keyword after the if statement.
• You can include multiple elseif blocks. You can also omit the
else block.
if condition1
code
elseif condition2
code
else
code
end A.J.R NDALAMA - 2023
19
Programming: For Loops
• Used to repeat a statement or a group of statements for a fixed number
of times
• When you run this code, the loop body executes three times as the loop
counter (c) progresses through the values 1:3 (1, 2, and 3).
20
A.J.R NDALAMA - 2023
Programming: while – Loops
• Used to execute a statement or a group of statements for an
indefinite number of times until the condition specified by while
is no longer satisfied.
total = 0;
k = 0;
while total < 1e4
k = k + 1;
total = 5*k^2 - 2*k + total;
end
fprintf('\nThe number of terms is : %d \n', k)
fprintf('The sum is : %d \n', total) 21
A.J.R NDALAMA - 2023
Programming: break statement
• The command break inside a for or while loop terminates the
execution of the loop even if the condition for execution of the loop
is true
• Here is a simple example
for k = 1:10
x = 50 - k^2;
if x < 0
break
end
y = sqrt(x)
end
fprintf('The loop terminated after %i passes\n',k)
22
A.J.R NDALAMA - 2023
Programming: continue statement
• The continue statement is
similar to the break statement, total = 0;
for i = 1:5
but instead of transferring n = input('Enter number: ');
control to the statement if (n < 0)
following the enclosing control disp('Ignoring! ');
structure, it only terminates the continue;
current iteration of the loop. end
total = total + n;
• Program execution resumes end
with the next iteration of the disp(['Total = ' num2str(total)]);
loop.
23
Programming: switch–case-
otherwise
• Provides logical branching for computations.
• A flag is used as a switch and the values of the flag make up the
different cases of execution:
color = input('color = ','s');
switch color %switch flag
case 'red' %case value1
c = [1 0 0] %block 1 computation
case 'green' %case value2
c = [0 1 0] %block 2 computation
case 'blue'
c = [0 0 1]
otherwise %otherwise
error('Invalid Choice of color')
end A.J.R NDALAMA - 2023
24
Live Scripts
• Live scripts are program files that contain your code, output,
and formatted text together in a single interactive environment called
the Live Editor.
• In live scripts, you can write your code and view the
generated output and graphics along with the code that produced it.
• Add formatted text, images, hyperlinks, and equations to create an
interactive narrative that you can share with others.
25
A.J.R NDALAMA - 2023
Live Scripts
26
Live Scripts
• To create a live script in the Live Editor, go to the Home tab and click
New Live Script .
• You also can use the edit function in the Command Window.
• For example, type edit [Link] to open or create the file
[Link].
• To ensure that a live script is created, specify a .mlx extension.
• If an extension is not specified, MATLAB® defaults to a file with .m
extension, which only supports plain code
27
A.J.R NDALAMA - 2023
Live Scripts: Display Output
• By default, MATLAB displays output to the right of the code.
• Each output is displayed with the line that creates it.
• To move focus between the code and the output using the keyboard,
press Ctrl+Shift+O.
• When scrolling, MATLAB aligns the output to the code that generates it.
• To disable the alignment of output to code when output is on the right,
right-click the output section and select Disable Synchronous Scrolling.
• To change the size of the output display panel, drag the resizer bar
between the code and output to the left or to the right.
28
A.J.R NDALAMA - 2023
Exercise Question 1
Write one live script for all questions. Questions should be
properly labelled in text format on the same script. Save
your scripts as [Link]
29
A.J.R NDALAMA - 2023
Exercise Question 2
30
Exercise Question 3
31
A.J.R NDALAMA - 2023
Exercise Question 3
Write a program in a script file that calculates the BMI of a person. The
program asks the person to enter his or her weight (lb) and height
(inc.).
The program displays the result in a sentence that reads: “Your BMI
value is XXX, which classifies you as SSSS,” where XXX is the BMI
value rounded to the nearest tenth, and SSSS is the corresponding
classification.
Use the program for determining the obesity of the following two
individuals:
a) A person 6 ft 2 in. tall with a weight of 180 lb.
b) A person 5 ft 1 in. tall with a weight of 150 lb. 32
A.J.R NDALAMA - 2023
Function Handles
• You can create a function handle to any function by using the at sign,
@, before the function name.
• You can then use the handle to reference the function.
• To create a handle to the function y = x + 2e-x -3, define the following
function file:
function y = f1(x)
y = x + 2*exp(-x) - 3;
33
A.J.R NDALAMA - 2023
Function Handles
• You can pass the function as an argument to another function. For
example, we can plot the function over 0 x 6 as follows:
>>plot(0:0.01:6,@f1)
>>fplot(@f1, [0 6])
34
A.J.R NDALAMA - 2023
Anonymous Functions
• Anonymous functions enable you to create a simple function without
needing to create an M-file for it.
• You can construct an anonymous function either at the MATLAB
command line or from within another function or script.
• The syntax for creating an anonymous function from an expression is:
fhandle = @(arglist) expr
35
A.J.R NDALAMA - 2023
Anonymous Functions
• The syntax for creating an anonymous function from an expression is:
fhandle = @(arglist) expr;
• Where arglist is a comma-separated list of input arguments to be
passed to the function and expr is any single, valid MATLAB
expression.
• This syntax creates the function handle fhandle, which enables
you to invoke the function.
36
A.J.R NDALAMA - 2023
Anonymous Functions
• For example, to create a simple function called sq to calculate the square
of a number, type:
>>sq = @(x) x.^2;
• To execute the function, type the name of the function handle, followed
by any input arguments enclosed in parentheses.
• For example:
>>sq(5) >>sq([5,7])
ans = ans =
25 25 49
37
A.J.R NDALAMA - 2023
Anonymous Functions
• Multiple-Input Arguments You can create anonymous functions having
more than one input.
• For example, to define the function 𝑥 2 + 𝑦 2 , type:
>>sqrt_sum = @(x,y) sqrt(x.^2 + y.^2);
>>sqrt_sum(3, 4)
ans =
5
38
A.J.R NDALAMA - 2023
Reading Assignment
• Read about:
• Primary functions.
• Subfunction.
• Nested functions.
• Private functions.
• fzero()
• Fminbnd()
W.J. Palm – MATLAB for Engineering
Applications (5th edition) Pp: 144 – 158;
39
A.J.R NDALAMA - 2023
Google Classroom:Computer
Applications
Code: iise6gx
Link:
[Link]
NTg0NjM1NzMw?cjc=iise6gx
40
THANK YOU
41
A.J.R NDALAMA - 2023