# How to calculate integrals in Matlab / Octave

To calculate the integral of a function f (x) in Matlab and Octave use int() function

int(f,x,inf,sup)

The parameters of the function are

• f is the function
• x is the integration variable
• inf is the lower extreme of integration
• sup is the upper extreme of integration

If the extremes of integration (inf, sup) are given, the function int () calculates a definite integral in the integration interval.

$$\int_{inf}^{sup} f(x) \ dx$$

If the integration extremes are not indicated, the int() function calculates a indefinite integral of the function f(x).

$$\int f(x) \ dx$$

Note. In Octave the int() function requires the installation and loading of the Symbolic library.

## Examples

Example 1 (indefinite integral)

Define the variable x of the function as a symbol using symbolic

syms x

Define the function f (x) = x2

f=x**2

Integrate the function with the int() function using the x integration variable

int(f)

The output result is the indefinite integral of the function

ans = (sym) x^3/3

The indefinite integral of f(x)=x2 with respect to the variable x is x3/3

$$\int x^2 \ dx = \frac{x^3}{3} + c$$

Example 2 (function of two variables)

Define two variables x and y

syms x y

Define a function with two variables f(x,y)=x*y

f=x*y

Integrate the function with respect to the variable y

int(f,y)

The output result is the integral

ans = (sym) x*y^2/2

The indefinite integral of f(x, y)=xy with respect to the variable y is xy2/2

$$\int x \cdot y \ dx = x \cdot \frac{y^2}{2} + c$$

Example 3 (definite integral)

Define a variable x

sym x

Define the function f(x)=x+1

f = x+1

Compute definite integral of the function with respect to the variable x using the extremes of integration inf = 1 and sup = 3

int(f,x,1,3)

The result is the definite integral of the function f (x) in the interval (1,3)

ans = (sym) 6

For a quick check

$$\int_1^3 x+1 \ dx = [ \frac{x^2}{2} + x ]^3_1 =$$

$$= \frac{3^2}{2} +3 - \frac{1^2}{2} - 1$$

$$= \frac{9+6-1-2}{2}$$

$$= \frac{12}{2}=6$$

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

Calculus in Matlab/Octave