MATLAB anonymous function analysis

In MATLAB, anonymous functions are also known as inline functions. It is a short function expression that does not require user definition, and is usually used for one-off simple calculations.

To create an anonymous function use the following syntax:

function_handle = @(input_arguments) expression

Here function_handleis a handle to a function, input_argumentsa list of input parameters, and expressionis the function body.

Here is an example to calculate the value of the sine function through an anonymous function:

>> sin_func = @(x) sin(x);
>> sin_func(pi/2)
ans =
     1

The above code defines an anonymous function sin_funcnamed , and then pi/2calculates the value of the sine function by passing in the parameter 1.

Any valid expression in MATLAB can also be used in an anonymous function. For example, we can write an anonymous function to calculate the sum of two numbers as follows:

>> sum_func = @(a, b) a + b;
>> sum_func(2, 3)
ans = 
     5

The above code defines an anonymous function sum_funcnamed , and then calculates their sum by passing in parameters and2 , and the calculated result is .35

Using anonymous functions can greatly simplify code writing and debugging, and make programs more readable. In addition to using regular input parameters, anonymous functions can also capture variables from the environment. These variables are read-only to anonymous functions because anonymous functions cannot change their values.

For example, the following code demonstrates how to define an anonymous function that uses external variables a:

>> a = 2;
>> squared = @(x) x^2 + a;
>> squared(3)
ans =
     11

The code above sets the value aof 2, which is then accessed in the anonymous function, enabling the function to calculate the square of the incoming argument plus the value aof .

When you create an anonymous function, MATLAB automatically determines the number of input arguments to the function and returns a handle to the function. This function handle can be called like a normal function, passing the necessary parameters.

When writing complex MATLAB code, anonymous functions can be a useful tool for quick temporary solutions, simple functions, or for testing code.
In addition to the basic usage described above, MATLAB's anonymous functions can also use some advanced features, such as function handles, variable scope, and recursive calls.

  1. function handle

A function handle in MATLAB is a pointer to a function, similar to a function pointer in C language. By using a function handle, you can pass a function as an argument or assign it to a variable in your code for later use.

For example, the following code demonstrates how to assign an anonymous function to fa variable and call that function from another function:

>> f = @(x) x^2 - 3*x + 5;
>> g = @(func, x) func(x);
>> g(f, 2)
ans =
     3

The code above first creates an anonymous function fnamed and then assigns this function to a variable g. Then we define gthe function , whose first parameter is a function handle and the second parameter is a number. Finally, by calling gthe function , the previously defined anonymous function and parameter values 2​​are passed to the function to calculate the result 3.

  1. variable scope

When using anonymous functions, it is sometimes necessary to capture variables in the current environment inside the anonymous function. By default, an anonymous function can only access input parameters from itself. However, when using anonymous functions, there are two ways to achieve variable sharing within functions:

(1) Use globaldeclarations to declare global variables. But this method is not very easy to use, because it destroys the encapsulation and portability of the code.

(2) nested functionCreate . Nested functions can access variables of the main function and do not need to declare variables in the function input parameter list.

For example, the following code demonstrates how to use a nested function to share local variables inside it with the input parameters of an anonymous function:

>> outer_func = @(a) nested_func(a);
>> function res = nested_func(b)
       res = b^2 + a;
   end
>> outer_func(4)
ans =
     20

The code above defines an anonymous function outer_funcnamed that apasses the parameter to the nested function nested_func. From here, nested_funcyou can access the input variables of outerthe function a. When we 4pass to outer_func, it calls the nested nested_funcfunction , which evaluates (4)^2+4=20and returns the result.

  1. recursive call

If your anonymous function is recursive, you must first pass it yourself using the function handle. This is necessary to make MATLAB emulate the function calling method of C and other programming languages. Here is an example:

>> factorial = @(n,factorialize) factorialize(n,factorial);
>> factorialize = @(n,factorial) n <= 1 ? 1 : n * factorial(n-1, factorial);
>> factorial(5,factorialize)
ans =
     120

The code above defines two anonymous functions, factorialand factorialize. factorialThe function calls the recursive subfunction with the first input argument and the function handle as arguments. And the recursive subfunction factorializecomputes the factorial of n.

In this case, we implemented a recursive function call by passing the function handle to itself.

Anonymous functions in MATLAB provide a convenient and flexible way to write small and neat code. You can use anonymous functions for any number of purposes such as evaluating simple expressions, writing test code, writing advanced functions, or parsing more complex data structures.

In addition to basic and advanced features, anonymous functions in MATLAB can also be used with some other common tools, libraries, and functions to better use and optimize the functions of MATLAB.

  1. Anonymous functions and arrays

Anonymous functions in MATLAB can be stored in arrays like other data types. This approach is very convenient because it enables you to easily pass a set of anonymous functions to another function, or access them by index.

For example, the following code demonstrates how to create and access an array of anonymous functions:

>> functions = {@(x) x^2, @(y) y^3, @(z) z^4};
>> functions{1}(4)
ans =
    16
>> functions{3}(2)
ans =
    16

The code above defines an array of anonymous functions functionsnamed , containing three different anonymous functions. Then, we use {}the operator to access specific functions in the array and pass arguments to them. The first example computes the square 4of and the second 2to the fourth power.

  1. Anonymous functions and cell arrays

Similar to arrays, if you need to create a container that holds different types of objects (such as matrices, functions, strings, etc.), cell arrays in MATLAB are a good choice.

For example, the following code creates a cell array of two strings and an anonymous function, and accesses some elements in the array:

>> mycell = {'hello', @(x,y) x^2+y^2, 'world'};
>> mycell{1}
ans =
    hello
>> mycell{3}
ans =
    world
>> mycell{2}(2,3)
ans =
    13

In this example, we create a cell array mycellnamed containing two strings and an anonymous function. Different elements in an array can be easily accessed by using {}the operator and indexing for access.

  1. Anonymous functions and fplot

MATLAB's fplotfunction is a very powerful tool for plotting function graphs. It also allows you to draw multiple lines, so you can use an array of anonymous functions to join multiple lines together.

For example, the following code shows how to define an array with two anonymous functions and use fplotto plot relationship between the two functions:

>> funcs = {@(x) sin(x), @(x) cos(x)};
>> fplot(funcs)

The code above defines an anonymous function array of two functions funcsnamed and uses fplotthe function to render the two functions into exactly one graphics window.

In general, MATLAB's anonymous function is a flexible, simple and powerful programming tool that can play an important role in many application scenarios. Try using anonymous functions in your program, they can make your project more compact, fast and easy to maintain.

In addition to these uses mentioned above, there are some other uses of anonymous functions in MATLAB:

  1. Anonymous functions and integral functions

integralThe function in MATLAB is a tool for numerical integration. It allows you to integrate different functions and returns exact results.

Because accepts integralonly one input parameter, when you need to evaluate a function with multiple input parameters, you can use an anonymous function to pack the parameters together.

For example, the following code demonstrates how to create an anonymous function with two parameters and use it to compute an integral:

>> myfunc = @(x,a) x*a + sin(x);
>> integral(@(x) myfunc(x,3),0,pi)
ans =
    12.9343

The code above defines an anonymous function myfuncnamed that takes two input parameters. We then use another anonymous function to combine the second argument ( a=3) with the first argument (a number in the range between 0and ), and use this function as input to the function, resulting in the exact result.πintegral

  1. Anonymous functions and cellfun functions

cellfunThe function in MATLAB is a tool for performing the same operation on each element in a cell array. cellfunTherefore, it can be useful when you want to use the same method for different types of data .

You can use an anonymous function inside cellfunthe function to specify what to do with the elements in the array. This way, you can process the data in any way you want without having to manually write loops or judgment statements.

For example, the following code demonstrates how to create a cell array containing different types of data and cellfunuse an anonymous function to calculate the square of each element:

>> mycell = {'hello', 5, [1 2 3], @(x) x^2};
>> cellfun(@(x) x^2, mycell)
ans =
      '???'    25    [1×3 double]    '@(x)x^2'

The code above defines a cell array mycellcalled that contains elements of different types. Then we use an anonymous function (x) x^2to calculate the square of each element in the array and store the result in another cell array.

  1. Anonymous functions and arrayfun functions

cellfunLike , arrayfunthe function in MATLAB is a tool for performing the same operation on each element in an array. But unlike cellfunworking cell arrays, arrayfunanonymous functions can be applied to plain numeric arrays of various object types.

For example, the following code demonstrates how to create an array of numbers and use an anonymous function to square each element in the array:

>> myarr = [1 2 3 4];
>> arrayfun(@(x) x^2, myarr)
ans =
     1     4     9    16

In this example, we define an array myarrcalled and use the anonymous function @(x) x^2to calculate the square of each element in the array. This anonymous function is then called through arrayfunthe function , and we end up with a new array containing the result of squaring each element.

In summary, using anonymous functions in MATLAB can help you write more compact, faster, and error-free code. You should now have a good understanding of and use of anonymous functions.

In addition to the application scenarios mentioned above, there are other ways to use anonymous functions in MATLAB, such as:

  1. Anonymous functions and filter functions

filterThe function in MATLAB is a very useful tool for processing digital filters of input signals. Because it accepts a filter function as an input argument, you can use anonymous functions to create custom numerical filters.

For example, the following code demonstrates how to use an anonymous function to define a simple numeric filter:

>> x = sin(2*pi*0.01*(0:999)); % 1000-sample sinewave
>> myfilter = @(x) [1 -0.5]*x'; % generate a simple filter kernel
>> y = filter(myfilter, 1, x);
>> plot(x)
>> hold on
>> plot(y)

In this example, we first generated a 1000-sample sine wave with a frequency of 0.01. Then, we define an anonymous function myfilternamed , which implements a simple linear numeric filter. Finally, we apply this filter to the input signal using filterthe function to get the filtered output.

  1. Anonymous functions and ode45 functions

ode45The function in MATLAB is a numerical method for solving ordinary differential equations. This function takes a function handle as an input parameter, so you can use anonymous functions to define differential equations.

For example, the following code shows how to use an anonymous function to define an initial value problem involving a differential equation and solve it using ode45the function :

>> f = @(t,y) [y(2); -y(1)];
>> [T,Y] = ode45(f, [0 10], [1 0]); % solve the ODE
>> plot(Y(:,1),Y(:,2)) % plot the solution

In this example, we create an anonymous function fnamed to represent this simple second-order ordinary differential equation. We then use ode45the function to numerically solve the equation and store the results in Tthe and Yvariables . Finally, we plot the trajectory of the solution Yin .

  1. Anonymous functions and quad functions

The MATLAB quadfunction is a tool for numerical integration, integralsimilar to the function. But it uses a different algorithm and can handle certain types of functions more precisely.

Perhaps most interestingly, in MATLAB, quadfunctions only accept function handles with one variable, which means that if you want to pass multiple input arguments to quada function , you must use an anonymous function to bundle them together.

For example, the following code demonstrates how to use an anonymous function to manually implement the formula for the area Rof radius , and use quadthe function to calculate the area:

>> R = 1; % set the radius of the circle
>> A = quad(@(theta) R^2*sin(theta),0,pi); % calculate the area of the circle
>> disp(['Area of a circle with radius ' num2str(R) ' is ' num2str(A)]) 
Area of a circle with radius 1 is 3.1416

In this example, we first define a variable Rcalled to represent the radius of the circle. We then manually computed the circle's area formula (theta) R^2*sin(theta)using , passing it as an input parameter to quadthe function, and got an exact answer.

In summary, MATLAB's anonymous functions can be combined with many common tools and functions and help simplify writing and processing common tasks. To learn more about anonymous functions and their usage in MATLAB, see the official MATLAB documentation or other tutorials on the web.

Of course, there are other scenarios where MATLAB anonymous functions can be used, such as:

  1. Anonymous functions and the fminsearch function

fminsearchThe function in MATLAB is an optimization tool for unconstrained minimization problems (that is, finding a local or global minimum). This function takes a function handle as an input parameter and returns its minimum value as output.

Because the function expects to accept a single vector argument, you can use an anonymous function to create a vector of input arguments for a multivariate minimization problem.

For example, the following code demonstrates how to use an anonymous function to implement Rosenbrock's function and use fminsearchthe function to minimize it:

>> f = @(x) 100*(x(2)-x(1).^2)^2 + (1-x(1)).^2;
>> x0 = [0 -1];
>> [x,fval] = fminsearch(f,x0);

In this example, we first define an anonymous function fnamed that implements a two-variable Rosenbrock function. We then choose an initial point x0and use fminsearchthe function to try to find the minimum point and the minimum of the objective function. Finally, the output is stored in the xand fvalvariables.

  1. Anonymous functions and the fsolve function

fsolveThe function in MATLAB is a tool for solving systems of nonlinear equations. This function takes a function handle as an input parameter and uses the Newton-Raphson method or other numerical techniques to find the roots of the system of equations.

If you need to customize the iteration function when solving a nonlinear system of equations, you can use an anonymous function to create this function handle.

For example, the following code demonstrates how to use an anonymous function to implement a nonlinear system of equations in two unknown variables and solve it using fsolvethe function :

>> f = @(x)[x(1)^2+x(2)^2-5; x(1)*x(2)-1];
>> x0 = [1 1];
>> x = fsolve(f,x0);

In this example, we first define an anonymous function fnamed , representing a simple system of nonlinear equations with two unknown variables. Then we choose an initial point x0and use fsolvethe function to try to find the roots of this system of equations. The final output is stored in xthe variable .

  1. Anonymous functions and ode15s functions

ode15sThe function in MATLAB is a numerical method for solving sparse Jacobian ordinary differential equations (ODEs). It can effectively handle large and complex models, and obtain high-precision calculation results in the shortest time.

Since ode15sthe function expects to accept a function handle containing a differential equation, it is very intuitive to use an anonymous function to define a differential equation.

For example, the following code demonstrates how to use an anonymous function to definek value), and then use ode15sthe function

>> f = @(t,y,k) [k(1)*y(1)^2-k(2)*y(1)*y(2); k(2)*y(1)*y(2)-k(1)*y(2)];
>> y0 = [10; 5];
>> k = [0.02; 0.03];
>> [t,y] = ode15s(@(t,y) f(t,y,k), [0 500], y0);

In this example, we first define an anonymous function fnamed to represent a Mass Action reaction network in a binary system. We then choose the initial state value y0, which contains two mass concentrations, and a vector of underlying rate constants describing the network. Finally we wrap the input function expression passed to the ode15sfunction into a new anonymous function, specifying the time zone [0 500]in which to compute the system's response.

In summary, using anonymous functions in MATLAB can help you write cleaner, more efficient, and more flexible code, while also making your code more readable. They can help simplify repetitive tasks, reduce code redundancy, and let you focus on solving the problem itself.

Guess you like

Origin blog.csdn.net/shaozheng0503/article/details/131115868
Recommended