MATLAB Portable Functions

From ControlTheoryPro.com

Jump to: navigation, search
Symbol.gif
MATLAB Portable Functions
Green carrot left.gif
All MATLAB Articles
Green carrot.jpg
In order to prevent spam, users must register before they can edit or create articles.



This section discusses inline functions, anonymous functions, and function handles. Each of these is 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. Inline and anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file.

1 Inline functions

An inline function is one way that a function can be created at the command or in a script:

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

To create a multi-variable inline function, send more inputs to the 'inline' function:

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

You cannot make an array of inline functions, MATLAB will tell you that you have too many inputs or do something weird like that.

2 Anonymous functions

A function can also 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)


3 Function Handles

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).

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.

TODO

TODO
How do you write a function that accepts a function handle?


TODO

TODO
How do you write an image to file without displaying it?