Learn R Programming

pracma (version 1.8.8)

trapz: Trapezoidal Integration

Description

Compute the area of a function with values y at the points x.

Usage

trapz(x, y)

cumtrapz(x, y)

Arguments

x
x-coordinates of points on the x-axis
y
y-coordinates of function values

Value

  • Approximated integral of the function from min(x) to max(x). Or a matrix of the same size as y.

Details

The points (x, 0) and (x, y) are taken as vertices of a polygon and the area is computed using polyarea. This approach matches exactly the approximation for integrating the function using the trapezoidal rule with basepoints x.

cumtrapz computes the cumulative integral of y with respect to x using trapezoidal integration. x and y must be vectors of the same length, or x must be a vector and y a matrix whose first dimension is length(x). Inputs x and y can be complex.

See Also

polyarea

Examples

Run this code
# Calculate the area under the sine curve from 0 to pi:
  n <- 101
  x <- seq(0, pi, len = n)
  y <- sin(x)
  trapz(x, y)                       #=> 1.999835504

  # Use a correction term at the boundary: -h^2/12*(f'(b)-f'(a))
  h  <- x[2] - x[1]
  ca <- (y[2]-y[1]) / h
  cb <- (y[n]-y[n-1]) / h
  trapz(x, y) - h^2/12 * (cb - ca)  #=> 1.999999969

  # Use two complex inputs
  z  <- exp(1i*pi*(0:100)/100)
  ct <- cumtrapz(z, 1/z)
  ct[101]                           #=> 0+3.14107591i

Run the code above in your browser using DataLab