MATLAB Programming/Portable Functions

From Wikibooks, open books for an open world
< MATLAB Programming
Jump to: navigation, search


This section discusses anonymous functions and function handles. Both of these are portable in that rather than having to write an equation multiple times in a program, you can just define it once and then call it whenever you want to use it. In addition, function handles in particular allow you to pass an equation to another function for direct evaluation as needed. Anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file.

Anonymous functions[edit]

An anonymous function can be created at the command or in a script:

>>f = @(x) 2*x^2-3*x+4;
>>f(3)
ans = 13

To make an anonymous function of multiple variables, use a comma-separated list to declare the variables:

>>f = @(x,y) 2*x*y;
>>f(2,2)
ans = 8

It is possible to make an array of anonymous functions in MATLAB 7.1 but this will become outdated soon so using this construct in a distributed program is not recommended.

To pass anonymous functions to other functions, just use the name of the anonymous function in your call:

>> f = @(t,x) x;
>> ode45(f, [0:15],1)

Function Handles[edit]

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[edit]

You can also write your own functions that accept function handles. Simply define them as variables in your header, and then call them 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