lettura simple

Anonymous functions in Octave

In this lesson, I will explain how to create anonymous functions in Octave.

What is an anonymous function? It is a mathematical function with one or more variables that you can define in a single line.

To create a function in Octave, use the following syntax:

name@(variables) expression

Start by writing the function name followed by the "@" symbol.

Then, specify the independent variables within parentheses and the expression of the function.

Let me provide you with a practical example. Define this anonymous function:

>> f = @(x,y) x^2+y^2

This function is called f and is a two-variable function with the expression x2+y2

$$ f(x,y) = x^2+y^2 $$

Note that in this example, I have used the name f, but you can give the function any name you like.

Once you have defined the function f(x,y), you can call it by passing specific parameters.

For example, type f(2,3) in the console and press enter.

>> f(2,3)

The function receives the parameters x=2 and y=3, calculates the result of the expression x2+y2, and displays the output.

ans = 13

In this case, the result of the function is 13 because

$$ f(x=2,y=3) = x^2 + y^3 = 2^2 + 3^2 = 4+9 = 13$$

You can call the function as many times as you like.

For example, type f(3,4).

>> f(3,4)

The function receives the parameters x=3 and y=4, returns the result of the expression, and displays the output.

ans=25

In this case, the result of the function is 25 because

$$ f(x=3,y=4) = x^2 + y^3 = 3^2 + 4^2 = 9+16 = 25 $$




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin