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.
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.
Let’s create a function that takes one input.
square = @(x) x.^2;result = square(5); % This will return 25fprintf('The square value is %.2f\n', result);
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.
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 7fprintf('The square value is %.2f\n', result);
The function above takes two arguments, adds them, and returns the value.
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);
In the code above:
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.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);
The cubed numbers are: [27, 216, 729, 1728]
The code will produce an error because of incorrect syntax.
The cubed numbers are: 27 216 729 1728
The cubed numbers are: 3, 6, 9, 12
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