MATLAB Programming/Portable Functions
Portable functions are expressions defined once, then called whenever it is needed regardless of the platform. Portable functions include anonymous functions, and function handles. A third form of portable functions which is being phased out is inline functions.
Anonymous functions can be created from the command line without a script.
>> convert_min_to_s = @(t) t*60; >> convert_min_to_s(4) ans = 240
Function 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 ampersand returns the handle of a function either built into Matlab or defined in an M-file.
>> sum_by_a_different_name = @sum; >> sum_by_a_different_name([3 3]) ans = 6 >> not_sum ([3 3]) ??? Undefined function or method 'not_sum' for input arguments of type 'double'.
Function Handles in m-files
If 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
Functions 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
Inline 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