polyfit: Fitting by Polynomial

Description Usage Arguments Details Value Note See Also Examples

View source: R/polyfit.R

Description

Polynomial curve fitting

Usage

1
2
3
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

poly, polyval

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  # 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)

Example output



pracma documentation built on Dec. 11, 2021, 9:57 a.m.