12.4. Anonymous functions#

An anonymous function is a small function consisting of a single expression. An anonymous function is declared using

function_name = @(argument) expression;

Anonymous functions can be declared anywhere in a MATLAB script file. To demonstrate this lets declare an anonymous function to triple a number. Enter the following code into your program.

% Anonymous functions
triple = @(x) 3 * x;

triple(4)

Run your program and you should see the following added to the command window.

ans =

    12

12.4.1. Returning an anonymous function#

Anonymous functions can be used when we want to return a function from another function. For example, lets say that we want a function that multiples the input x by some number k. Enter the following into the end of your program

% ------------------------------------------------------------------------
function anonymous_function = multiply(x)

anonymous_function = @(k) k * x;

end

and make a call to this function by entering the following code before the function declarations.

% Returning an anonymous function
my_double = multiply(2);
triple = multiply(3);
quadruple = multiply(4);

fprintf("%d\n", my_double(5))
fprintf("%d\n", triple(5))
fprintf("%d\n", quadruple(5))

Run your program and your should see the following added to the command window.

10
15
20

12.4.2. Exercises#

Exercise 12.8

Write an anonymous function that calculates the value \(y\) using the following quadratic for different input values of \(x\)

\[ y = 2x^2 - 3x + 4. \]

Use your function to calculate \(y\) when:

  1. \(x = 2\)

  2. \(x = 3\)

Exercise 12.9

Write a function called power_function() that returns a function which raises an input \(x\) to the power \(n\). Use this function to create the following functions:

  1. square() that calculates \(x^2\)

  2. cube() that calculates \(x^3\)

  3. quartic() that calculates \(x^4\)

Use your functions to calculate the square, cube and quartic of 123.