Professional Documents
Culture Documents
Lecture 9:
Function files
Last Lecture
2
Lecture Outline
Input Output
4
Function files – why do you want them?
5
Function files – why do you want them?
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 = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
14
Function files – The ‘return’ command
Prime_nmbs = [2 3 5 7 11 13 17 19 23 29 31];
%Above is listed the first 11 prime numbers
function y = display_Value(x)
if (isa(x,'char') ~= 0)
error('Input is Char. Input needs to be an integer')
end
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;
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
%-------------------------
function mean = avg(x,n)
%AVG subfunction
mean = sum(x)/n;
• 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)
• Here’s an example:
>> feval('example_eq_lec7',3.67)
ans =
-1.10605140804024
>> 23
Lecture Summary
24