lettura simple

How to find the derivative of a function in Octave

In this guide I'll explain how to calculate the derivatives of a function in Octave.

To calculate the derivative you have to use the command diff()

diff(function, variable, order)

The first parameter is the expression of the function, the second is the derivation variable, the third is the order (first derivative, second, third, ...).

Note. To use this command you must first have Symbolic installed on Octave.

I'll give you a practical example

Define the variable x symbol

syms x

Now calculate the first derivative of the function x3+x2+x using the function diff()

diff(x**3+x**2+x,x,1)

Note. In the expression, the symbol for exponentiation is **

The result is the first derivative of the function.

ans = (syms)

3⋅x^2 + 2⋅x + 1

Now calculate the second derivative of the same function.

Rewrite the same command by changing the last parameter to 2.

diff(x**3+x**2+x,x,2)

The result is the second derivative of the function.

ans = (syms)

2⋅(3⋅x + 1)

Now calculate the third derivative

Type the same command again by changing the last parameter to 3

diff(x**3+x**2+x,x,3)

The result is the third derivative of the function.

ans = (syms)

6

You can also derive functions with two or more variables f(x, y).

For example, define the symbol of two variables

syms x y

Calculates the first derivative of the function x2y2 respect to x

diff(x**2*y**2,x,1)

The result is the partial derivative 2xy2.

ans = (syms)

2xy**2

If this short guide by Nigiara on GNU Octave helped you keep following us.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin