What are anonymous functions in MATLAB?

In MATLAB, anonymous functions are functions that define other small, unnamed functions without creating separate files. They are useful for defining quick, one-time-use functions or passing functions as arguments to other functions.

How to create anonymous functions

We can create anonymous functions using the @(inputs) expression syntax, where inputs are the function’s input arguments and expression is the function’s operation.

Let’s go through different types of anonymous functions and see their examples.

Single input

Let’s create a function that takes one input.

square = @(x) x.^2;
result = square(5); % This will return 25
fprintf('The square value is %.2f\n', result);

Explanation

In the code above:

  • Line 1: We create an anonymous function @(x) x.^2 that takes one input x and returns its square. The function is then assigned to the variable square. We can call square like a regular function.

  • Line 3: We call square, which passes 5 as an input, and stores it in the result variable.

  • Line 5: We print the value of result.

Multiple inputs

Anonymous functions can also take multiple inputs. Let’s go through an example and see how it works.

addition = @(a, b) a + b;
result = addition(3, 4); % This will return 7
fprintf('The square value is %.2f\n', result);

The function above takes two arguments, adds them, and returns the value.

Commonly used functions

These functions are commonly used with functions like arrayfun, cellfun, map, filter, and others where a function is applied element-wise or to each element of an array or cell array.

Let’s go through an example and see how it works.

values = [1, 2, 3, 4, 5];
squared_values = arrayfun(@(x) x.^2, values);
fprintf('The square values are %.2f\n', squared_values);

Explanation

In the code above:

  • We call arrayfun, which applies the anonymous function, @(x) x.^2, to each element of the values array, resulting in a new array containing the squares of each element.
Q

What is the output of the following MATLAB code?

nums = [3, 6, 9, 12];
cubed_nums = arrayfun(@(x) x.^3, nums);

fprintf('The cubed numbers are: ');
disp(cubed_nums);
A)

The cubed numbers are: [27, 216, 729, 1728]

B)

The code will produce an error because of incorrect syntax.

C)

The cubed numbers are: 27 216 729 1728

D)

The cubed numbers are: 3, 6, 9, 12

Conclusion

Anonymous functions offer a convenient way to define small, one-time-use functions or pass functions as arguments, enhancing the flexibility and efficiency of code development.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved