In the previous post, I showed you lambda function in python and how to combine it with built-in filter function. As you may know, lambda is also known as anonymous function. In this post, we take a look at using anonymous functions in MATLAB/OCTAVE.

It is really easy, in MATLAB/OCTAVE you need to define the anonymous function using a handle sign (i.e. @): it would be something like this:

f = @(x)(x^3 + x^2 + x + 1)

It can be seen that after the @, the parameters are listed between parenthesis. Then you mention the function embraced with another couple of parenthesis.

After you defined the anonymous function, now it can be used in many ways. For instance you can evaluate it, like this:

feval(f,2.5) ans = 25.375

You can also, calculate integrals, for instance:

quad(f,0,1) ans = 2.0833

Let’s do all that in one line of code:

quad(@(x)(x^3 + x^2 + x + 1),0,1) ans = 2.0833

Now consider a case that you have more than a variable in your function. It is simple, NO?

f=@(x,y)(x^2 + y^3 + x*y) feval(f,2,0.5) ans = 5.1250

And the last and the most interesting tip here. In MATLAB/OCTAVE we can have array of anonymous functions, for instance:

f={@(x) (x+2); @(y) (3*y + y^0.5); @(z) (sin(z)+cos(z)); @(x,y,z)(sin(x+y)/(z+0.5))} x=0.2; y=0.3; z=5; f{1}(x) ans = 2.200 f{2}(y) ans = 1.4477 f{3}(z) ans = -0.67526 f{4}(x,y,z) ans = 0.087168

Now, go crazy!!!