MATLAB Lesson 9 - Anonymous functions

Anonymous functions provide a easy way to define a relatively simple function with one or more input arguments, parameters, and a single output argument. The anonymous function may be passed as an argument to other functions, but otherwise is only available in the workspace where it was defined.

Input arguments for anonymous functions

To create an anonymous function MATLAB uses

fname = @(arg1, arg2, arg3, ...) expression

There may be one or more input arguments specified in the parentheses after the @ character. The expression must produce a single object, which can be a scalar, vector, matrix or other more complicated structure.

Define the anonymous function

h(u, v) = sin(3 u) cos(v + 4).

Define an anonymous function h with two input arguments.

Note the use of the elementwise operator .* so the function will work with input arguments which are arrays of the same size.

>>  h = @(u, v) sin(3*u).*cos(v+4)

The names of the arguments does not matter, except within the expression defining the function. Thus an alternative definition for the function h is

>>  h = @(x, y) sin(3*x).*cos(y+4)

Parameters which are not arguments

If the expression defining the anonymous function contains variables which are not arguments to the function, then the values of those variables when the function is defined are used.

Define an anonymous function h as above, but which uses the values of the parameters a and b in place of the constants 3 and 4.

The values of the variables a and b when the function is defined are used.

>>  h = @(u, v) sin(a*u).*cos(v+b)


What does the following sequence of commands produce?

Define the variable a with value 2.

Define the anonymous function f using the current value of a, which is 2.

This calculates 32 = 9

Change the value of the variable a to 4.

The definition of the function f has not changed, so this still produces 9.

>>  a = 2;
>>  f = @(x) x.^a
>>  f(3)
>>  a = 4;
>>  f(3)

 

Warnings

 

Self-test Exercise

Write an anonymous function to calculate

decay(t) = cos(a t) e - b t

using
  • a = pi and b = 0.5, then
  • a = 2 pi and b = 0.5,

Answer:
a = pi;

b = 0.5;

decay = @(t) cos(a*t) .* exp(-b*t)
a = 2*pi;

decay = @(t) cos(a*t) .* exp(-b*t)

Use the mouse to select the text between the word "Answer" and here to see the answer.

Summary

Anonymous functions are very useful for defining relatively simple functions which are used just within one MATLAB M-file. They can have several input arguments, including parameters whose values are determined when the function is defined, but one output argument which can be an array.