This example shows how to integrate a set of discrete velocity data numerically using
trapz to approximate the total distance traveled. The
integral family only accepts function handles as inputs, so those functions cannot be used with discrete data sets. Use
trapz when a functional expression is not available for integration.
View the Velocity Data
Consider the following velocity data and corresponding time data.
vel = [0 .45 1.79 4.02 7.15 11.18 16.09 21.90 29.05 29.05 ... 29.05 29.05 29.05 22.42 17.9 17.9 17.9 17.9 14.34 11.01 ... 8.9 6.54 2.03 0.55 0]; time = 0:24;
This data represents the velocity of an automobile (in m/s) taken at 1 s intervals over 24 s.
Plot the velocity data points and connect each point with a straight line.
figure plot(time,vel,'-*') grid on title('Automobile Velocity') xlabel('Time (s)') ylabel('Velocity (m/s)')
The slope is positive during periods of acceleration, zero during periods of constant velocity, and negative during periods of deceleration. At time
t = 0, the vehicle is at rest with
vel(1) = 0 m/s. The vehicle accelerates until reaching a maximum velocity at
t = 8 s of
vel(9) = 29.05 m/s and maintains this velocity for 4 s. It then decelerates to
vel(14) = 17.9 m/s for 3 s and eventually back down to rest. Since this velocity curve has multiple discontinuities, a single continuous function cannot describe it.
Calculate the Total Distance Traveled
trapz performs discrete integration by using the data points to create trapezoids, so it is well suited to handling data sets with discontinuities. This method assumes linear behavior between the data points, and accuracy may be reduced when the behavior between data points is nonlinear. To illustrate, you can draw trapezoids onto the graph using the data points as vertices.
xverts = [time(1:end-1);time(1:end-1);time(2:end);time(2:end)]; yverts = [zeros(1,24);vel(1:end-1);vel(2:end);zeros(1,24)]; hold on p = patch(xverts,yverts,'b','LineWidth',1.5);
trapz calculates the area under a set of discrete data by breaking the region into trapezoids. The function then adds the area of each trapezoid to compute the total area.
Calculate the total distance traveled by the automobile (corresponding to the shaded area) by integrating the velocity data numerically using
distance = trapz(time,vel)
distance = 345.2200
The distance traveled by the automobile in
t = 24 s is about 345.22 m.