Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

polyfit

Fitting by Polynomial


Description

Polynomial curve fitting

Usage

polyfit(x, y, n)

polyfix(x, y, n, xfix, yfix)

Arguments

x

x-coordinates of points

y

y-coordinates of points

n

degree of the fitting polynomial

xfix,yfix

x- and y-coordinates of points to be fixed

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. In polyfit, if x, y are matrices of the same size, the coordinates are taken elementwise. Complex values are not allowed.

polyfix finds a polynomial that fits the data in a least-squares sense, but also passes exactly through all the points with coordinates xfix and yfix. Degree n should be greater or equal to the number of fixed points, but not too big to avoid ‘singular matrix’ or similar error messages

Value

vector representing a polynomial.

Note

Please not that polyfit2 is has been removed since 1.9.3; please use polyfix instead.

See Also

Examples

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

## Not run: 
  n <- 3
  N <- 100
  x <- linspace(0, 2*pi, N); y = sin(x) + 0.1*rnorm(N)
  xfix <- c(0, 2*pi); yfix = c(0, 0)

  xs <- linspace(0, 2*pi); ys <- sin(xs)
  plot(xs, ys, type = 'l', col = "gray",
	   main = "Polynom Approximation of Degree 3")
  grid()
  points(x, y, pch='o', cex=0.5)
  points(xfix, yfix, col = "darkred")

  p0 <- polyfit(x, y, n)
  lines(xs, polyval(p0, xs), col = "blue")

  p1 <- polyfix(x, y, n, xfix, yfix)
  lines(xs, polyval(p1, xs), col = "red")

  legend(4, 1, c("sin", "polyfit", "polyfix"),
         col=c("gray", "blue", "red"), lty=c(1,1,1))
## End(Not run)

pracma

Practical Numerical Math Functions

v2.3.3
GPL (>= 3)
Authors
Hans W. Borchers [aut, cre]
Initial release
2021-01-22

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.