
polyfit(x, y, n)polyfit2(x, y, n = 1, p0 = NULL)
p0 = [x0, y0]
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.
poly
, polyval
# 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