MATLAB Programming/Portable Functions
Functions in MATLAB
editA function is a group of sequential expression statements (a.k.a pseudo-algorithm) that are formed together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function MUST be the same. Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more than one output arguments.
The sntax of functions as followed
function [y1,...,yN] = myfunc(x1,...,xM)
where syntax declares a function named myfunc that accepts inputs x1,...,xM and returns outputs y1,...,yN .
This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.
Create Functions in Separate Files
editTo create a new function, at "Home" tab, click on "New" ---> "Functions" It will create a template looks like the following:
function [outputArg1,outputArg2] = untitled2(inputArg1,inputArg2)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
outputArg1 = inputArg1;
outputArg2 = inputArg2;
end
Declare a function
editTo demonstrate a function usefulness, we are going to take a hypothetical situations ,
Recently, in your class there are some exchange students from America whom are consistently complaining the weather is hot outside, when they check on their weather app, they exclaimed the weather is 100 degrees outside. But as to the people who never uses the imperial units before, you might wonder, what is the temperature outside right now ?
So, to solve the question, it might be a good time to create a custom functions to convert from Fahrenheit to Celsius .
First of all, we must know the conversion formula from Fahrenheit to Celsius which is given as:
At "Home" tab, click on "New" ---> "Functions"
function [Ce] = convertTemp(Fa)
% Convert from Fahrenheit to Celcius
Ce = (Fa-32)*(5/9);
end
Click on save button to save the functions as convertTemp.m file
Note: The filename MUST be same as function name or else it won't work !
Later, on the Current Folder Panel, select the directory where you save the function files just now.
Calling a function
editTo call the newly created function, do the following: On the Command Window Panel, type this command as shown
>> convertTemp(100)
ans =
37.7778
Hence, the weather outside is almost 38 Celsius degrees.
Benefits of functions
editWhy this is beneficial, you might ask ?
Well, from this exercise , you can see that you can just type function name to execute the calculation especially for repetitive tasks.
Just imagine for example above, it will be a real time saver to just type function convertTemp instead of manually typing formula each tims.
Type of functions
editThe type of functions includes such as:
- Anonymous Functions
- Local Functions
- Nested Functions
- Private Functions
- Inline function (Phased out in future version)
Anonymous Functions
editAnonymous functions allow you to define a function without creating a program file, as long as the function consists of a single statement. A common application of anonymous functions is to define a mathematical expression without creating a separate files.
Here is how the anonymous syntax looks like
output = @(arguments) expression
where, output = output to be returned arguments = required inputs to be passed expression = a single formula/logic
It can accept multiple inputs and return one output. They can contain only a single executable statement.
Here, we have an examples of converting Fahrenheit to Celsius.
>> convTempF = @(Fa) (Fa-32)*(5/9);
>> convTempF(88)
ans =
31.1111
>> convTempF(60)
ans =
15.5556
Another example here is using anonymous function to convert minute to seconds (NOTE: 1 minute is equal to 60 seconds)
>> convert_min_to_s = @(t) t*60;
>> convert_min_to_s(4)
ans =
240
Local functions
editSometimes in mathematics, you might be encountering an issue where you might find a use case where function that are better to be calculated within it's own function .
Rather than running separate functions to get one output, you just need to run just one function to get the multiple output. This is where local functions comes in.
To clarify further , in a function file, the first function in the file is called the main or parent function.
Additional functions within the file are called local functions, and they can occur in any order after the main function. Local functions are only visible to other functions in the same file. These are equivalent to subroutines in other programming languages, and are sometimes called sub-functions.
The application for this local functions is in a complex function, it would be easier to be broken down to smaller piece of functions and we are certain that the functions are going to be used in same functions and not at other functions.
Examples of local functions
editTo illustrate an examples, we will create a function statistik which will take in a series of number and return an output of basic function of statistic such as max , min, average and standard deviation. We will give it just a sting of random numbers and it will produce all the usual statistic results.
First of all, we need to create a function named statistik , follow the instruction here at Create Functions in Separate Files
function [max,min,ave,stdev] = statistik(v) % this is the main function and can call to other local functions
% The function where it takes arguments of series and it will calculate the basic statistic info
% min function selects the smallest number in the series
% max function selects the largest number in the series
% ave function calculate the average of the series
% stdev function calculate the standard deviations
max = maxf(v);
min = minf(v);
ave = avef(v);
stdev = stdevf(v);
end %end of function statistik
function a=maxf(v)
%Sub function selects the largest number in the series
a = max(v);
end %end of function maxf
function b= minf(v)
%Sub function selects the smallest number in the series
b = min(v);
end %end of function minf
function c = avef(v)
%Sub function to calculate the average of the series
c = mean(v);
end %end of function avef
function d = stdevf(v)
%Sub function to calculate the std dev of the series
d = std(v);
end %end of function stdevf
After creating function statistik in a separate file, we generate a random set of number inside the Command Window using randi function
>> V = randi(50,1,10)
V =
25 29 12 23 49 28 27 12 25 32
We call the function statistik as followed inside the Command Window:
[maximum,minimum,average,stdeviation]=statistik(V)
maximum =
49
minimum =
12
average =
26.2000
stdeviation =
10.4435
Although you cannot call a local function from the command line or from functions in other files, you can access its help using the help function.
Specify names of both the file and the local function, separating them with a > character.
>> help statistik>avef
Sub function to calculate the average of the series
Nested Function
editNested functions are functions that are nested entirely inside the main functions.
The primary difference between nested functions and local functions is that nested functions can use variables defined in parent functions without explicitly passing those variables as arguments.
Requirements of nested functions
edit(a) To nest any function in a program file, all functions in that file must use an end statement.
(b) A nested function can't be defined inside any of the program control statements, such as if/elseif/else, switch/case, for, while, or try/catch.
(c) A nested function either directly by function name , or using a function handle that you created using the @ operator (refer to anonymous function).
(d) All of the variables in nested functions or the functions that contain them must be explicitly defined. That is, you cannot call a function or script that assigns values to variables unless those variables already exist in the function workspace.
Examples of nested functions
editWe have a hypothetical situations where we need to estimate the weight of metal ingots which are in cylindrical shape.
First, before we started on figuring out the metal ingots weight, we need to break down the problems into smaller piece.
To figure out the weight of the metal, we need to figure out the density and before figuring out density we need to figure out volume of the metal.
To start off, before we start to know the volume of ingot, we first calculate the surface area of the cylinder base which is circle.
Area of circles is defined as
,r is radius of base circle
We can use the area of circle to calculate the volume of cylinder
,h is height of cylinder.
Lastly, we use the volume and density to calculate the weight
where D is density.
In MATLAB, we formulate the formula such as these.
Note: For the nested functions beside main funtions, we need to indent the functions .
Editor -> Indent.
Note:
function[]=ingot_calc()
%This function is to calculate the price of an cylindrical ingot
r = 3 ; % radius of base circle
h = 10; % height of ingot
d = 4.5;% density of the metal
ar = circle_area;
vo = volume;
we = weight;
function a = circle_area
%calculate area of circle for the radius
a=pi*r*r;
at=['Area of circle is ',num2str(a,'%8.2f') , ' cm2'];
disp(at)
end
function v = volume
%calculate volume
v = ar* h;
vt=['Volume of the ingot is ',num2str(v,'%8.2f') , 'cm3'];
disp(vt)
end
function w = weight
%calculate weight
w = vo*d;
wt=['The weight of ingot is ',num2str(w,'%8.2f'), ' g'];
disp(wt)
end
end
When we calling ingot_calc function in the command window, it should display the values
>> ingot_calc
Area of circle is 28.27 cm2
Volume of the ingot is 282.74cm3
The weight of ingot is 1272.35 g
Inline Functions
editInline functions are currently being phased out. Anonymous functions should be used instead. Inline functions are included here for information purposes.
>> convert_s_to_ms = inline('x*1000','x'); >> convert_s_to_ms(20) ans = 20000
Function Handles
editFunction handles are doubles serving as an abstract reference to the function. Handles allow an equation to be passed to another function for direct evaluation. Anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file.
The ampersat returns the handle of a function either built into Matlab or defined in an M-file.
To illustrate example, we need to build a tent as shown on the picture but we need to figure out what is the amount of tarp that are needed to build the carnival tent.
Therefore, we will create two separate functions which take the radius and slant height of cone (cone) plus radius and height of cylinder (cylinder) .
To refresh the your memory, formula for cone surface (remember we focus slanting area and ignore the base area) is
and cylinder surface (remember that one side of circle of cylinder is not calculated) is
, where the r is the shared radius of cylinder and cone, l is the length of slanting height of cone and finally h is height of cylinder.
Follow steps in Create Functions in Separate Files to start create totalsurftent
function [surfcone,surfcylin] = totalsurftent(r,l,h)
% The function where it takes arguments of r,l,h to calculate surface area of cylinder and cone
% r is radius
% l is slanting lenth of cone
% h is cylinder height
surfcone = sacone(r,l);
surfcylin = sacylin(r,h);
end
function on=sacone(r,l)
%Sub function to calculate face area of cylinder
on = pi*r*l;
end
function yl= sacylin(r,h)
%Sub function to calculate face area of cylinder
yl = (2*pi*r*h)+(pi*r^2);
end
We can know the surface area by typing following commands:
>> %Testing out the custom functions totalsurftent
>> [areacone,areasurfcylin] = totalsurftent(3,3,3)
areafcone =
28.2743
areacylin =
84.8230
Function Handles in m-files
editIf you are not familiar with m-files, then skip this and come back.
A function handle passes an m-file function into another function. This of course lets you have more control over what's passed there, and makes your program more general as it lets you pass any m-file (as long as it meets other requirements like having the right number of input arguments and so on). The functionality is similar to that of function pointers in C++.
To pass an m-file to a function, you must first write the m-file, say something like this:
function xprime = f(t,x) xprime = x;
Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @ symbol as follows:
>> ode45(@myfunc, [0:15], 1)
One advantage of using function handles over anonymous functions is that you can evaluate more than one equation in the m-file, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions limit you to one equation.
How to write a function that accepts a function handle
editFunctions can accept function handles. To do this define them as variables in your header, and then call the handles as if they were functions:
% myadd adds two variables together function result = myfunc(func, a, b); result = func(a, b); [in a separate m-file] function sum = myadd(a, b) sum = a+b;
The command you send to myfunc looks like this:
>> result = myfunc(@myadd, 1, 2); result = 3