GE 209 - COMPUTER PROGRAMING USING
MATLAB
Lectures
Chapter 6
User-defined functions
Introduction
• A function is a piece of computer code that accepts an input argument from the
user and provides output to the program.
• It allows us to: program efficiently, to avoid rewriting the computer code for
calculations that are performed frequently
E.g.: the function sin(x)
• User-defined functions are stored as M-files and can be accessed by MATLAB if
they are in the current folder or on MATLAB’s search path.
• User-defined functions compute a returned variable (output) based on specified
values of the function arguments (inputs)
6.1 Creating function M-files
Both built-in MATLAB functions and user-defined MATLAB functions have the same
structure. Each consists of: a name; a user-provided input; and calculated output.
Each function M-file must start with a function definition line that contains:
• The word function
• A variable that defines the function output
• A function name
• A variable used for the input argument
The structure of a function [OutputVariables] = FunctionName(InputVariables)
Function file is as follow: % Comments
MATLAB Expression(s)
• OutputVariables is a comma-separated list of the names of the output variables;
• InputVariables is a comma-separated list of the names of the input variables.
• There is no terminating character or expression for the function such as the end statement
• The function file may be stored in any directory and must have the same name as the
function name with extension “.m”: FunctionName.m
Impor tant notes about functions
The file name must be the same as the function name.
All of the MATLAB naming conventions we learned for naming variables apply to naming user-
defined functions. Reserved names cannot be used; i.e. cos, exp …
The names of functions should be chosen so that they are meaningful and indicate what the function
does.
Typical lengths of function names are between 9 and 20 characters and should employ standard or
consistent conventions.
The proper choice of function names can also minimize the use of comments within the function itself
Before using a function M-file, it must be saved into the current folder
Any function of the current folder is accessible by a script file, other functions or from the
command window
6.1.2 Comments
As with any computer program, you should comment your code so that it is easy to follow.
However, in a MATLAB function, the comments on the line immediately following the very first line
serve a special role.
These lines are returned when the help function is queried from the command window.
• Consider, for example, the following function:
function [mints, results] = f(seconds, x)
%This function converts seconds to minutes
results = x./60;
Querying the help function from the command window
help f
returns
This function converts seconds to minutes
Example
Define a function named poly3, save it in the current folder then calculate its value for x = 1
function output = poly3(x)
%This function calculates the value of a
% third-order polynomial
output = 3*x.^3 + 5*x.^2 - 2*x +1;
In command window, type:
>> x = 1; >> x = 1:5;
>> poly3(x) >> y = poly3(x)
MATLAB will return MATLAB will return
y=
ans = 7
7 41 121 265 491
6.1.3 Functions with Multiple Inputs and Outputs
MATLAB functions may require multiple inputs and may return multiple outputs
Example 1: Calculate the area of a triangle
function triangle_area = TriAr(base,height)
% This function calculates the area of triangle
% base and height must be the same size matrices
a = (base .*height)/2;
triangle_area = a;
In command window, type:
>> x=1:5;
>> y=5:9;
>> z=TriAr(x,y)
z=
2.5000 6.0000 10.5000 16.0000 22.5000
• Here, x and y represent the base and height, respectively
• z represents the output (triangle area)
Example 2: Motion of a particle
function [dist, vel, accel] = motion(t) If you call the function without specifying all
outputs, only the first output will be returned:
% This function calculates the distance, velocity, and %
acceleration of a particle for a given value of t motion(10)
% assuming all 3 parameters are initially 0. ans =
accel = 0.5 .*t; 83.3333
vel = t.^2/4;
dist = t.^3/12;
The following commands will returns all outputs results =
t accel vel dist
time=[Link]; 0 0 0 0
10 83.333 25 5
[distance, velocity, acceleration] =motion(time); 20 666.67 100 10
results = [time',distance', velocity', acceleration'] 30 2250 225 15
6.1.4 Functions with No Input or No Output
most functions need at least one input and return at least one output
In some cases no inputs or outputs are required.
90
1
120 60
0.8
0.6
For example, consider this function, which draws a star in polar coordinates: 150
0.4
30
0.2
function [] = star( ) 180 0
theta = pi/2:0.8*pi:4.8*pi;
r = ones(1,6); 210 330
polar(theta,r)
240 300
270
The square brackets indicate that the output of the function is an empty matrix (i.e., no value is
returned).
The empty parentheses tell us that no input is expected.
If, from the command window, you type: star , then no values are returned, but a figure window
opens showing a star drawn in polar coordinates .
6.1.5 Determining the Number of Input and Output Arguments
Sometimes you need to know the number of input arguments or output values associated with a
function. MATLAB provides two built-in functions for this purpose.
The nargin function determines the number of input arguments in either a user-defined function
or a built-in function. The name of the function must be specified as a string, as, for example:
nargin('sin')
ans = 1
When nargin is used inside a user-defined function, it determines how many input arguments were
actually entered. This allows a function to have a variable number of inputs.
The nargin function allows the programmer to determine how to create the plot, based on the number
of inputs.
The nargout function is similar to nargin, but it determines the number of outputs from a function:
6.1.6 Local Variables
Function files are script files that create their own local and independent workspace within
MATLAB.
Variables defined within a function are local variables to that function.
• They neither affect nor are they affected by the same variable names being used in any
script or other function.
• All of MATLAB’s functions are of this type.
• The exception is those variables that are designated global variables.
For example, consider the g function described below:
The variables a, x , y , and output are
function output = g(x,y) local variables. They can be used
% This function multiplies x and y together
% x and y must be the same size matrices inside the g function, but they are not
a = x .*y;
output = a stored in the workspace
6.1.7 Global Variables
• Variables that are defined in the workspace may be transferred to a function by passing them
through the input arguments
• But in some instances, the number of different variables needed by a function can become large.
• In addition, it is more appropriate to keep some variables as a parameters that can be monitored
from outside the function (in the script or workspace)
• In these cases, it may be beneficial for the function to share the global memory of the script or
function or to create access to global variables for use by various functions.
• This access is provided by the keyword: global
• Global variables are normally available to all parts of a computer program, but, as a precaution,
MATLAB requires declaring the global variables in both script and function files
Example
x = cos(at ) + b
Consider the following two equations that are to be computed in a function:
y = x +c
The values of x and y are to be returned by the function.
The function will be named ComputeXY
• In this example, the variable t is the main variable. It will be passed to the function as an input argument
• The scalars a, b and c will be parameters that can be adjusted at any time in the main program
• a, b and c will be defined as global variables
function scr ipt The scr ipt to call this function become:
function [x, y] = ComputeXY(t) global a b c
% Computation of - a = 1.4; b = 2; c = 0.75;
% x = cos(at)+b t=0:pi/4:pi;
% y = |x|+c [u, v] = ComputeXY(t)
% Scalars: a, b, c
% Vectors: t, x, y
Note:
global a b c
x = cos(a*t)+b; The blank spaces between the global variable names must be used
y = abs(x)+c; instead of commas.
6.1.8 Accessing M-File Code
The functions provided with MATLAB are of two types.
One type is built in, and the code is not accessible for us to review.
The other type consists of M-files, stored in toolboxes provided with the program.
We can see these M-files (or the M-files we’ve written) with the command type.
For example, the sphere function creates a three-dimensional representation of a sphere; thus,
type sphere
or
type('sphere')
returns the contents of the sphere.m file:
6.2 Creating your own Toolbox of Functions
When you call a function in MATLAB, the program first looks in the current folder to see if the
function is defined. If it can’t find the function listed there, it starts down a predefined search path,
looking for a file with the function name.
To view the path the program takes as it looks for files, from the menu bar select
File Set Path or type pathtool
As you create more and more functions to use in your programming, you may wish to modify the path
to look in a directory where you’ve stored your own personal tools.
For help to find out the path, just add
help addpath
6.3 Anonymous Functions and Function Handles
An anonymous function is a user-defined function that is defined and written within the computer
code (not in a separate function file) and is then used in the code.
Anonymous functions can be defined in any part of MATLAB (in the Command Window, in script
files, and inside regular user-defined functions).
An anonymous function is a simple (one-line) user-defined function (not an M-file).
• To create an anonymous function, use the following structure:
Name_fun :name of the anonymous function.
Name_fun = @ (arglist) expression arglist :A list of input arguments (independent variables).
expression : mathematical expression.
The @ symbol alerts MATLAB that Name_fun is a function.
The name of the function appear in the workspace as a function_handle
Examples
Function with 1 input Function with 2 inputs
Circle_area = @ (radius) pi*radius.^2 F_xy=@(x,y) 2*x.^2-4*x.*y+y.^2;
radius=1:5; x=linspace(0,3,5);y=x;
Circle_area(radius) F_xy(x,y)
Function with 3 outputs
% Output in 3 rows (Fahrenheit, Kelvin and Rankine scale)
Temp = @(celcius) [9/5*celcius+32; celcius+273; 9/5*celcius+491.67];
m=Temp(30:35)
6.4 Function Functions
MATLAB’s function functions have an odd, but descriptive name. They are functions that require
other functions as input.
One example of a MATLAB built-in function function is the function fplot. This function requires
two inputs: a function or a function handle, and a range over which to plot.
Examples:
• Plotting the function log in the interval [0.1, 10] • Plotting a 5th degree polynomial
ln=@(x) log(x) poly5 = @(x) -5*x.^5 + 400*x.^4 + 3*x.^3 + 20*x.^2 - x + 5;
fplot(ln,[0.1, 10]) fplot(poly5,[-30,90])
6.5 SUBFUNCTIONS
When the function keyword is used more than once in a function file, all the
additional functions created after the first function key word are called sub-
functions.
The expressions comprising the first use of the function keyword is called the main
function.
It is the only function that is accessible from the command window, scripts, and
other function files
A main script can also contain 1 or more sub-functions. In this case, these
functions must be defined at the end of the script code
The sub functions are accessible only to the main function or to the main script
and to other sub functions within the main function file
Example: Compute the mean and standard deviation of a vector of numerical values
function [m, s] = MeanStdDev(dat) % Main function
n = length(dat);
m = meen(dat, n);
s = stdev(dat, n);
function m = meen(v, n) % Sub function 1 n
m = ∑ xk
m = sum(v)/n; n k =1
function sd = stdev(v, n) % Sub function 1 n 2 2
1/2
m = meen(v, n); % Calls a sub function
s= ∑ k x - nm
n - 1 k =1
sd = sqrt((sum(v.^2)-n*m^2)/(n-1));
A script that uses this function and sub functions is:
% main script
v = [1, 2 , 3, 4];
[m, s] = MeanStdDev(v)
Note: It is also possible to define all these functions (MeanStdDev, meen and stdev) in the main script;
all as a sub-functions