Learn R Programming

pracma (version 1.8.6)

polyfit: Fitting by Polynomial

Description

Polynomial curve fitting

Usage

polyfit(x, y, n)

polyfit2(x, y, n = 1, p0 = NULL)

Arguments

x
x-coordinates of points
y
y-coordinates of points
n
degree of the fitting polynomial
p0
Point p0 = [x0, y0]

Value

  • vector representing a polynomial

Details

polyfit finds the coefficients of a polynomial of degree n fitting the points given by their x, y coordinates in a least-squares sense.

polyfit2 finds a polynomial that fits the data in a least-squares sense, but also passes through y0 for x=x0. In polyfit, if x, y are matrices of the same size, the coordinates are taken elementwise. Complex values are not allowed.

See Also

poly, polyval

Examples

Run this code
# Fitting the sine function by a polynomial
  x <- seq(0, pi, length.out=25)
  y <- sin(x)
  p <- polyfit(x, y, 6)
  
# Plot sin and fitted polynomial
  plot(x, y, type="b")
  yf <- polyval(p, x)
  lines(x, yf, col="red")
  grid()

Run the code above in your browser using DataLab