Dr. Young's trapz Tutorial

The Matlab function trapz uses the trapezoid rule to solve a definite integral. The format is

I=trapz(x,y);

where I is the value of the integral, x is an array of the independent variable, and y is an array of the dependent variable.

trapz is very useful when you have data points you want to integrate. It can also be used to integrate an equation. For example, integrate the following equation from r = 1 to r = 10

g = 5r2

To integrate this equation, first make an array of the independent variable, r, which goes from 1 to 10. Then calculate the dependent variable, g, at each value of r. The more points you have between 1 and 10, the more accurate your answer will be. Once you have made the two arrays, use trapz to integrate. Here is my m-file that does this.

clear;
format compact;
rfinal = 10.0;     % set limits of integration
rinitial = 1.0;
step = (rfinal - rinitial)/10000;     % calculate step size, use 10000 steps
r = rinitial : step : rfinal;     % fill independent variable array
g = 5 * r.^2;     % fill dependent variable array

I = trapz(r,g);     % integrate

Note that I is the integral of 5r2dr. When you run the m-file, your output should look like this:

» trapztut
I =
    1.6650e+003
»

Now let's integrate the same equation again, but go from r = 10 to r = 1 instead. Just change rfinal to 1.0 and rinitial to 10.0 in the m-file above. Now your output should look like this:

» trapztut
I =
    -1.6650e+003
»

Because we let Matlab calculate the step size, it automatically counted "down" from 10 to 1 when necessary, and the integral has the correct negative value.

  • Send mail to Dr. Young: valy@bobcat.ent.ohiou.edu.
  • Return to ChE 201 home page.
  • (Last modified on 4/26/00)