# How to calculate a derivative in Matlab / Octave

To calculate the derivative of a function f (x) in Matlab and Octave use the function diff()

diff(f,x,n)

The parameters of the function are

• f is the function
• x is the derivation variable
• n is the degree of derivation

Note. The order of derivation is equal to 1 by default (first derivative). The function variables must be defined as symbols. In Octave the diff function requires the installation and loading of the Symbolic library.

## Examples

Example 1 (first derivative)

Define a variable as symbols

syms x

Define the function x2

f=x**2

Derive the function with the diff () function and specify the variable for differentiation.

diff(f,x)

The result is the first derivative.

ans = (sym) 2*x

Example 2 (second derivative)

To calculate the second derivative of the previous function, specify the order of the derivative equal to 2.

diff(f,x,2)

The output is the second derivative.

ans = (sym) 2

Example 2 (third derivative)

To calculate the third derivative of a function, specify the order of the derivative equal to 3.

diff(f,x,3)

The output result is the third derivative.

ans = (sym) 0

https://how.okpedia.org/en/matlab/how-to-calculate-a-derivative-in-matlab--octave Report us an error or send a suggestion to improve this page

Calculus in Matlab/Octave