You are on page 1of 24

ENG 1060

Computing for Engineers

Lecture 9:
Function files
Last Lecture

• Last lecture, we considered


three topics:
– Using MATLAB Data files
– Creating 2-D Graphs of your data
– Creating 3-D Graphs of your data

– By now, you should be able


to save files containing your data
and create graphs of your results.

2
Lecture Outline

• Today we briefly discuss function


files
– Function files are an improved type
of M-file
– Examples will be presented

At the end of this lecture you should


be able to write and use function
files.
3
Function files – why do you want them?
• When you use MATLAB functions such as
inv, abs, tan and sqrt, MATLAB takes the
variables that you pass to the function,
computes the required results using your
input, and then passes these results back
to you.
• The commands evaluated by the function,
as well as variables created within the
function are hidden from you.
• All you see is what goes in, and what
comes out.

Input Output
4
Function files – why do you want them?

• This is different from the script M-files


which we have looked at up until now.

• Script M-files don’t take any input


unless it is user input, or from a data
file

• Script M-files clearly display variables


which were created as the M-file was
executed.

5
Function files – why do you want them?

Essentially, functions act as ‘black boxes’


6
Function files – why do you want them?

Once the function is correctly


written users only have to
know how to input data, and
what form the output will take.
This is very useful when
developing complex systems,
or where there are several
users of a system.

7
Function Files – A simple example:
• Often, in statistics, we need to know the
mean and standard deviation of a group of
values.
• We can write a function which will return
both the mean and the standard deviation
of an array of values x:

function [mean,stdev] = stat(x)


%STAT Interesting statistics.
To start with we will
n = length(x); only concentrate on the
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);
highlighted section of
coding.
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
8
Function Files – A simple example:

function [mean,stdev] = stat(x)


%Generates the Mean and standard %deviation for an
array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

• A function file starts with the command


function. This informs MATLAB that this is a
function file and not a script M-file. In general
the command may be written:
function [output variable list] = function_name (input variable list)
9
Function Files – A simple example:

function [mean,stdev] = stat(x)


%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

• Comments which are made immediately below


the first line will be printed when a user types
‘help function_name’, for example:
>> help stat
Generates the Mean and standard
deviation for an array input x 10
Function Files – A simple example:

function [mean,stdev] = stat(x)


%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

In general, whenever a user types into the command


window
help function_name
MATLAB will print all commented lines up to the first
executable line
11
Function Files – A simple example:

function [mean,stdev] = stat(x)


%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

• The next lines contain the executable commands.


– Note that the variable n is said to be local to the
function and is invisible to the end user of the
function.
– The variables mean and stdev are output to the
user.
12
Function Files – A simple example:
• What happens when a user wishes to use
your function?
• Here is an example in the command
window.
>> x = [0.1 2 .3 9 1.5 3 8 5 1 9 6.1 100.2]
x=
1.0e+002 *
Columns 1 through 4
0.00100000000000 0.02000000000000 0.00300000000000 0.09000000000000
Columns 5 through 8
0.01500000000000 0.03000000000000 0.08000000000000 0.05000000000000
Columns 9 through 12
0.01000000000000 0.09000000000000 0.06100000000000 1.00200000000000
>> [mn, std] = stat(x)
mn =
12.10000000000000
std =
26.75144855890986
>>
13
Function Files – Some rules:
• The function M-file name must be the same as the
function name (e.g. The previous example must be
called stat.m)

• Function M-file names may have up to 63 characters

• Function names must begin with a letter, they cannot


contain spaces or punctuation characters

• The first line of a function M-file is called the function-


declaration line and must contain the word function
followed by the calling syntax of the function.

14
Function files – The ‘return’ command

• Functions will finish after the last line in the


file is executed or whenever a return
statement is encountered:
function y = find_lowest_common_denom(x)
%Returns the lowest common denominator of x

Prime_nmbs = [2 3 5 7 11 13 17 19 23 29 31];
%Above is listed the first 11 prime numbers

if x == 0 | x == 1 % Check for invalid input


disp('Please Enter an integer > 1.')
return;
end

for i = 1:length(Prime_nmbs) %i will go from 1 to 11


if (mod(x,Prime_nmbs(i)) == 0)
y = Prime_nmbs(i); return;
end
end 15
Function files – The ‘error’ command
• A function can abort operation and return control
to the command window by using the command
error:

function y = display_Value(x)

if (isa(x,'char') ~= 0)
error('Input is Char. Input needs to be an integer')
end

if (x-round(x) == 0) % check if x is integer


disp('This is an integer.');
else
error('Input is float. Input needs to be an integer')
end
y •= x;
This function will produce error messages unless
the input is of an integer type.

16
Subfunctions
function [mean,stdev] = stat(x)
%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

Functions can also contain subfunctions

Subfunctions are written in the same file as


the main function, and can only be used by
the main function.
17
Subfunctions
function [mean,stdev] = stat(x)
%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

Subfunctions also have a function


declaration line. This has the same
format as the main function
declaration line. 18
Subfunctions
function [mean,stdev] = stat(x)
%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

While it is good to comment your code,


they will not be visible if an end user
types help subfunction_name, because
the sub function is invisible to the end
user. 19
Subfunctions
function [mean,stdev] = stat(x)
%Generates the Mean and standard
%deviation for an array input x
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;

The main function may call upon


the subfunction just as easily as it
would call upon any other
function.
20
Function Files – An example:
• Imagine we have to evaluate the following
function in order to find the value of y, given a
value of x.

• A plot of the
function is given:

21
Function Files – An example:
• We can easily write this equation into a
function file, for example:
function y = example_eq_lec7(x)
%This function defines the example equation.
y = (sin(x) - cos(x).*cos(x)).* exp(-x/30)

• Many inbuilt MATLAB functions require a


user – defined function in order to
operate.

• An example is the MATLAB function


feval.
22
Function Files – An example:

• feval evaluates the user defined


function for a given input value,
it’s syntax is as follows:
feval(‘user_function_name’,x)

• Here’s an example:
>> feval('example_eq_lec7',3.67)
ans =
-1.10605140804024
>> 23
Lecture Summary

• Today you learnt how to write your


own function files.
– Function files are essentially ‘black
boxes’ which make programming easier
– You also learnt how to exit from a
function using the keywords return and
exit.
– Next lecture we consider engineering
examples using MATLAB.

24

You might also like