MATLAB:Anonymous Function

From PrattWiki
Revision as of 15:22, 11 July 2008 by DukeEgr93 (talk | contribs)
Jump to navigation Jump to search

MATLAB has a feature that lets you develop an analytical expression of one or more inputs and either assign that expression to a variable or pass it as an argument to a function. The @ symbol lets you create an anonymous function of any number of variables by giving the @ symbol, followed by a variable list, followed by the expression the function is meant to calculate. This method is good for relatively simple functions that will not be used that often and that can be written in a single expression. It is similar to creating an MATLAB:Inline Function with some significant differences.

Syntax

The syntax for building an anonymous function is to put the @ symbol, the variable list, and the expression all on one line. To give the anonymous function a name, simply put the function's name on the left side of an equal sign and the anonymous function on the right. For example, if you want \(c(a,b,\theta)\), to return \(\sqrt{a^2+b^2-2ab\cos(\theta)}\), you could create a function c by building an anonymous function and assigning it to the variable cas follows:

c = @(a, b, theta) sqrt(a.^2+b.^2-2*a.*b.*cos(theta))

MATLAB will respond with:

c = 
    @(a,b,theta)sqrt(a.^2+b.^2-2*a.*b.*cos(theta))

indicating that the variable c is now actually a function_handle that points to an anonymous function which takes three arguments. You can now use the function by putting numbers in for the arguments - for example:

SideThree = c(2, 3, pi/6)

will return

SideThree =
    1.6148

You can also use that function to return entire matrices. For example, the commands:

[x,y] = meshgrid(0:.1:2, 0:.1:2);
mesh(x, y, c(x, y, pi/4));
xlabel('Side 1');
ylabel('Side 2');
zlabel('Side 3');
title('Triangle Third Side vs. Sides Surrounding a 45^o Angle (mrg)')
print -depsc InlineExamplePlot

will produce the graph:

InlineExamplePlot.png

MATLAB Help File

Part of the MATLAB help file for using anonymous functions is[1]

FUNHANDLE = @FUNCTION_NAME returns a handle to the named function,
     FUNCTION_NAME. A function handle is a MATLAB value that provides a
     means of calling a function indirectly. You can pass function
     handles in calls to other functions (which are often called function
     functions). You can also store function handles in data structures for
     later use (for example, as Handle Graphics callbacks). A function
     handle is one of the standard MATLAB data types. Its class is
     'function_handle'.
 
     FUNHANDLE = @(ARGLIST)EXPRESSION constructs an anonymous function and
     returns a handle to that function. The body of the function, to the 
     right of the parentheses, is a single MATLAB expression. ARGLIST is a
     comma-separated list of input arguments. Execute the function by
     calling it by means of the returned function handle, FUNHANDLE. For
     more information on anonymous functions, see "Types of Functions" in
     the MATLAB Programming documentation.

Notes

  • Anonymous functions do access variables in the workspace at the time of creation. For example, note how the commands work
>> a = 3
a =
     3

>> b = @(x, y) a*x+y
b = 
    @(x,y)a*x+y

>> b(1, 2)
ans =
     5

This is vastly different from using an inline function:

>> binline = inline('a*x+y', 'x', 'y')
binline =
     Inline function:
     binline(x,y) = a*x+y

>> binline(1, 2)
??? Error using ==> inlineeval at 15
Error in inline expression ==> a*x+y
??? Error using ==> eval
Undefined function or variable 'a'.

Error in ==> inline.subsref at 27
    INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr,
    INLINE_OBJ_.expr);

Note, however, that the function handle is not a function of the workspace variable - that is, b is not a function of a nor will it change if a changes later:

>> a = 100
a =
     100

>> b(1, 2)
ans =
     5
  • Anonymous functions can only have one expression and can only return a single variable (though that variable can be a matrix).

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References

  1. Quoted from MATLAB help file for function_handle