Many MATLAB users struggle to understand how anonymous functions work and how they can be used effectively in their code.
Anonymous functions are a powerful tool in MATLAB that can simplify code, improve readability, and make it easier to reuse code in different contexts. However, many users find anonymous functions confusing and struggle to use them effectively.
In this article, we will introduce you to the world of anonymous functions in MATLAB and show you how to use them to write cleaner, more concise, and more powerful code.
Whether you are a beginner or an experienced MATLAB user, this guide will help you get up to speed with anonymous functions and take your coding skills to the next level.
So let’s dive in and explore the exciting world of anonymous functions in MATLAB!
What is an anonymous function in MATLAB?
In MATLAB, an anonymous function is a type of function that is defined without being associated with a specific file or function name. Anonymous functions are often used as quick, one-time use functions or as arguments to other functions.
Anonymous functions are created using the
@(arguments) expression syntax. Here,
arguments is a comma-separated list of input arguments that the function expects, and
expression is the MATLAB code that is executed when the function is called.
The syntax looks like this:-
myFun = @(arg1, arg2, …) expression
Once created, the anonymous function can be assigned to a variable (in this case
myFun) and called like any other MATLAB function.
myFun = @(x) x^2 + 1;
result = myFun(3); % result will be 10
Anonymous functions can also be used as arguments to other functions that expect a function handle. For example, the
fminsearch function in MATLAB takes an anonymous function as its first argument to minimize the function.
fun = @(x) (1-x(1))^2 + 100*(x(2)-x(1)^2)^2;
x0 = [0,0];
[x,fval] = fminsearch(fun,x0);
In the example above,
fun is an anonymous function that defines the Rosenbrock function, and
fminsearch is used to find the minimum value of this function starting from
Why use anonymous functions in MATLAB?
Anonymous functions are a powerful MATLAB tool that can help simplify code and make it more flexible and reusable.
Anonymous functions in MATLAB are used for a variety of reasons.
Here’s a table summarizing the main reasons why anonymous functions are used in MATLAB:-
|Passing functions as arguments||Anonymous functions are useful when you need to pass a small function as an argument to another function.|
|Creating simple one-liners||Anonymous functions can be created in a single line of code, and they can be used to create simple, one-off functions without the need to create a separate function file.|
|Creating closures||Anonymous functions can sometimes improve performance by reducing the overhead of calling a separate function file.|
|Creating local functions||Anonymous functions can be used to define local functions within a larger function. This can help to encapsulate functionality and make code more modular and readable.|
|Simplifying code||Anonymous functions can simplify code and make it more readable and maintainable.|
|Increasing flexibility||Anonymous functions can increase the flexibility of your code by allowing you to define functions on-the-fly.|
|Encapsulating functionality||Anonymous functions can help to encapsulate functionality and make code more modular and reusable.|
|Improving performance||Anonymous functions are useful when passing a small function as an argument to another function.|
How do you create an anonymous function handle in MATLAB?
In MATLAB, you can create an anonymous function handle using the “@” symbol followed by a list of input arguments and an expression that specifies the function’s output.
The basic syntax for creating an anonymous function handle in MATLAB is:-
myfunc = @(input_arg1, input_arg2, …) expression
myfunc is the handle to the anonymous function,
input_arg2, etc. are the input arguments to the function, and
expression is the mathematical expression that defines the output of the function.
For example, to create an anonymous function that squares its input, you can use the following code:-
square = @(x) x^2;
This creates an anonymous function handle
square that takes one input argument
x and returns its square.
You can then call the function using the handle and passing an argument to it, like this:-
result = square(3);
This will set
result to 9, the square of 3.
How to add two anonymous functions in Matlab
In Matlab, you can add two anonymous functions by defining a new one that adds the outputs of the two anonymous functions.
Here is an example:-
% Define two anonymous functions
f1 = @(x) x^2;
f2 = @(x) x^3;
% Define a new anonymous function that adds the outputs of f1 and f2
f3 = @(x) f1(x) + f2(x);
% Test the new function
x = 2;
y = f3(x); % y = 12 (i.e., 2^2 + 2^3 = 4 + 8 = 12)
In the example above, we defined two anonymous functions
f2 that compute the squares and cubes of their input values, respectively.
We then defined a new anonymous function
f3 that takes an input value
x, applies both
x, and returns their sum. Finally, we tested the new function
f3 by applying it to the input value
x=2, which resulted in
Here’s another example of adding two anonymous functions in Matlab:-
% Define two anonymous functions
g1 = @(x) sin(x);
g2 = @(x) cos(x);
% Define a new anonymous function that adds the outputs of g1 and g2
g3 = @(x) g1(x) + g2(x);
% Test the new function
x = pi/4;
y = g3(x); % y = sqrt(2)/2 + sqrt(2)/2 = sqrt(2)
In this example, we defined two anonymous functions
g2 that compute the sine and cosine of their input values, respectively. We then defined a new anonymous function
g3 that takes an input value
x, applies both
x, and returns their sum.
Finally, we tested the new function
g3 by applying it to the input value
x=pi/4, which resulted in
y=sqrt(2). This is because
sin(pi/4) = cos(pi/4) = sqrt(2)/2, so
g3(pi/4) = sqrt(2)/2 + sqrt(2)/2 = sqrt(2).
How to call anonymous functions in Matlab?
In MATLAB, you can define an anonymous function using the
@ symbol, followed by the input arguments and the function definition.
Here’s an example:-
f = @(x) x^2;
In this example, we’re defining an anonymous function
f that takes one input argument
x and returns
To call the anonymous function, you can simply use the name of the function and pass in the input arguments:-
result = f(3);
This will call the anonymous function
f with an input argument of
3 and return the result
You can also pass an anonymous function as an argument to other functions:-
result = arrayfun(@(x) x^2, [1 2 3 4]);
In this example, we’re using the
arrayfun function to apply the anonymous function
@(x) x^2 to each element of the array
[1 2 3 4]. The result will be a new array
[1 4 9 16] containing the squares of the original elements.
Examples of anonymous functions in Matlab
In MATLAB, anonymous functions are defined using the
@(arguments) expression syntax.
Here’s a table with examples of anonymous functions in MATLAB:-
|A simple anonymous function that squares its input.|
|An anonymous function that takes two inputs and returns their sum.|
|An anonymous function that takes a single input and returns the sum of its sine and cosine.|
|An anonymous function that implements the sigmoid function commonly used in machine learning.|
|An anonymous function that applies a function (in this case, squaring) to each element of an array input.|
|An anonymous function that returns only the positive elements of an array input.|
|An anonymous function that shuffles the elements of an array input.|
|An anonymous function that returns the sum of the squares of the elements of an array input.|
Note that the
@(x) syntax defines an anonymous function that takes a single input variable
x. The input variable can be any valid MATLAB variable name, and can be followed by additional input variables (e.g.,
The body of the anonymous function follows the input variable(s), and can contain any valid MATLAB code.
What are two common uses of anonymous functions in Matlab?
Here’s a table outlining two common uses of anonymous functions in MATLAB:-
|Common Use Cases||Description|
|1. Passing Functions as Inputs||Anonymous functions are often used to pass functions as inputs to other functions in MATLAB. This is useful in cases where a function needs to be customized for a particular use case, and creating a separate function for this purpose would be cumbersome. Anonymous functions can be defined inline and passed as arguments to a variety of MATLAB functions, such as |
|2. Creating Shortcuts for Repeated Code||Another common use for anonymous functions in MATLAB is to create shortcuts for frequently used code. By defining an anonymous function, you can encapsulate a block of code and give it a name that can be reused throughout your script or function. This can help to reduce code duplication and make your code more readable. For example, the following code defines an anonymous function that squares its input: |
What is the difference between function and anonymous function in Matlab?
In MATLAB, a function is a named block of code that performs a specific task and can be called from other parts of the program. A function has a name, input arguments, and output arguments. It is typically defined in a separate M-file.
On the other hand, an anonymous function is a function that is not defined with a name. It is defined within a single MATLAB expression and is created using the
@(arguments) expression syntax. Anonymous functions are useful when you need to define a small function without having to create a separate M-file.
The key difference between a function and an anonymous function is that a function has a name and can be called from anywhere in the program, while an anonymous function is defined within a single expression and can only be used in the scope where it is defined.
Another difference is that a function can have multiple statements, while an anonymous function is limited to a single expression.
Steps to Write Anonymous Function in Matlab
In MATLAB, you can create anonymous functions using the “@” symbol followed by a list of input arguments and an expression.
Here are the steps to create an anonymous function in MATLAB:-
Step 1:- Open MATLAB and create a new script or function file.
Step 2:- Type the “@” symbol followed by the list of input arguments in parentheses. For example, to create an anonymous function that takes two input arguments, x and y, you would write:-
Step 3:– After the input arguments, type an expression that uses the input arguments. For example, to create an anonymous function that returns the sum of two numbers, you would write:
@(x,y) x + y
Step 4:- You can save the anonymous function to a variable by assigning it using the “=” operator. For example:
myFunc = @(x,y) x + y
This will save the anonymous function to the variable “myFunc” and you can call it later by passing in values for x and y.
Here is an example of an anonymous function that takes an input argument “x” and returns the square of “x”:-
mySquare = @(x) x^2
You can then call this function by passing in a value for “x”, for example:-
This will return the value 9.
Advantages of Anonymous Functions in Matlab
In Matlab, anonymous functions are functions that are not associated with a file, and they are defined using the
here’s a table on the advantages of anonymous functions in MATLAB:-
|Concise syntax||Anonymous functions can be defined in a single line of code, which can make code easier to read and write.|
|Scoped variables||Anonymous functions can access variables defined in the same scope as the function, which can simplify code by reducing the need for passing variables as arguments.|
|Code reuse||Anonymous functions can be used to define small, reusable pieces of code that can be used multiple times in a script or function.|
|Callback functions||Anonymous functions are commonly used as callback functions, which are functions that are triggered by user interactions (such as clicking a button) or other events (such as the completion of a computation).|
|Closures||Anonymous functions can create closures, which are functions that remember the values of variables in their enclosing scope, even after the enclosing function has completed execution. This can be useful for implementing stateful algorithms or maintaining complex data structures.|
In conclusion, anonymous functions in Matlab offer a powerful tool for creating concise and reusable code. They allow you to define and manipulate functions without creating a separate file or function handle.
By using anonymous functions, you can streamline your code, make it more readable, and reduce the chances of errors. Whether you are a beginner or an experienced programmer, anonymous functions are a valuable technique to add to your toolbox.
With the knowledge and examples in this article, you can start implementing anonymous functions in your Matlab code today and take your programming skills to the next level.