# MATLAB Trapz

The MATLAB function trapz (x, y, n) where y is the integral for x, approximates the integral of a function y=f(x) using the trapezoidal rule, and n (optional) performs integration along with dimension n.

### Example1

Use the MATLAB function trapz (x, y) to approximate the cost of the integral and by comparison with the exact value, evaluate the percent error when n=5 and n=10.

Solution

The exact value is found from For the approximation using the trapezoidal rule, we let x5represent the row vector with n=5, and x10 the vector with n=10, that is, ∆x =1/5 and ∆x=1/10, respectively. The corresponding values are denoted as y5and y10, and the areas under the curve as area5 and area10, respectively.

Create the following Script

MATLAB display the following result:

The percent error when ∆x =1/5 is used is The percent error when ∆x =1/10 is used is ### Example2

The integral where τ is a dummy variable of integration, is called the error function, and it is used extensively in communications theory. Use the MATLAB trapz (x, y) function to find the area under this integral with n=10 when the upper limit of integration is t=2.

Solution

Create the following Script

MATLAB displays the following result:

### Example3

The i-v (current-voltage) relation of a non-linear electrical machine is given by where v(t)=sin3t.

By any means, find

• The instantaneous power is
p(t)=v(t)i(t)=0.1 sin3t(e0.2sin3t-1)
• The energy is the integral of the instantaneous is An analytical solution of the last integral is possible using integration by parts, but it is not easy. We can try the MATLAB int (f, a, b) function where f is a symbolic expression, and a and b are the lower and upper limits of integration, respectively.

When MATLAB cannot found a solution, it returns a warning. For example, MATLAB returns the following message when integration is attempted with the symbolic expression of equation

When this script is executed, MATLAB show the following message.

Next, we will find and sketch the power and energy by the trapezoidal rule using the MATLAB trapz (x, y) function. For this example, we choose n=100, so that ∆x=1/100. The MATLAB script below will compute and plot the power.

The power varies in a uniform fashion as shown by the plot of figure The MATLAB script below computes and plots the energy.

Thus, the value of the energy is 0.1013 joule. The energy is shown in figure: ### Feedback   