Learn R Programming

pracma (version 0.2-2)

polyfit: Fitting by Polynomial

Description

Polynomial curve fitting

Usage

polyfit(x, y, n)

Arguments

x
x-coordinates of points
y
y-coordinates of points
n
degree of the fitting polynomial

Value

  • vector representing a polynomial

Details

Calculates the coefficients of a polynomial of degree n fitting the points given by their x, y coordinates in a least-squares sense. if x, y are matrices of the same size, the coordinates are taken elementwise. Complex values are not allowed.

See Also

polydef, 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