Next: Miscellaneous Functions, Previous: Derivatives / Integrals / Transforms, Up: Polynomial Manipulations [Contents][Index]

Octave comes with good support for various kinds of interpolation,
most of which are described in Interpolation. One simple alternative
to the functions described in the aforementioned chapter, is to fit
a single polynomial, or a piecewise polynomial (spline) to some given
data points. To avoid a highly fluctuating polynomial, one most often
wants to fit a low-order polynomial to data. This usually means that it
is necessary to fit the polynomial in a least-squares sense, which just
is what the `polyfit`

function does.

- Function File:
`p`=**polyfit***(*`x`,`y`,`n`) - Function File:
*[*`p`,`s`] =**polyfit***(*`x`,`y`,`n`) - Function File:
*[*`p`,`s`,`mu`] =**polyfit***(*`x`,`y`,`n`) Return the coefficients of a polynomial

`p`(`x`) of degree`n`that minimizes the least-squares-error of the fit to the points`[`

.`x`,`y`]If

`n`is a logical vector, it is used as a mask to selectively force the corresponding polynomial coefficients to be used or ignored.The polynomial coefficients are returned in a row vector.

The optional output

`s`is a structure containing the following fields:- ‘
`R`’ Triangular factor R from the QR decomposition.

- ‘
`X`’ The Vandermonde matrix used to compute the polynomial coefficients.

- ‘
`C`’ The unscaled covariance matrix, formally equal to the inverse of

`x’`*`x`, but computed in a way minimizing roundoff error propagation.- ‘
`df`’ The degrees of freedom.

- ‘
`normr`’ The norm of the residuals.

- ‘
`yf`’ The values of the polynomial for each value of

`x`.

The second output may be used by

`polyval`

to calculate the statistical error limits of the predicted values. In particular, the standard deviation of`p`coefficients is given by`sqrt (diag (s.C)/s.df)*s.normr`

.When the third output,

`mu`, is present the coefficients,`p`, are associated with a polynomial in`xhat`= (`x`-`mu`(1)) /`mu`(2)

where`mu`(1) = mean (`x`), and`mu`(2) = std (`x`).This linear transformation of

`x`improves the numerical stability of the fit.**See also:**polyval, polyaffine, roots, vander, zscore.- ‘

In situations where a single polynomial isn’t good enough, a solution
is to use several polynomials pieced together. The function
`splinefit`

fits a peicewise polynomial (spline) to a set of
data.

- Function File:
`pp`=**splinefit***(*`x`,`y`,`breaks`) - Function File:
`pp`=**splinefit***(*`x`,`y`,`p`) - Function File:
`pp`=**splinefit***(…, "periodic",*`periodic`) - Function File:
`pp`=**splinefit***(…, "robust",*`robust`) - Function File:
`pp`=**splinefit***(…, "beta",*`beta`) - Function File:
`pp`=**splinefit***(…, "order",*`order`) - Function File:
`pp`=**splinefit***(…, "constraints",*`constraints`) -
Fit a piecewise cubic spline with breaks (knots)

`breaks`to the noisy data,`x`and`y`.`x`is a vector, and`y`is a vector or N-D array. If`y`is an N-D array, then`x`(j) is matched to`y`(:,…,:,j).`p`is a positive integer defining the number of intervals along`x`, and`p`+1 is the number of breaks. The number of points in each interval differ by no more than 1.The optional property

`periodic`is a logical value which specifies whether a periodic boundary condition is applied to the spline. The length of the period is`max (`

. The default value is`breaks`) - min (`breaks`)`false`

.The optional property

`robust`is a logical value which specifies if robust fitting is to be applied to reduce the influence of outlying data points. Three iterations of weighted least squares are performed. Weights are computed from previous residuals. The sensitivity of outlier identification is controlled by the property`beta`. The value of`beta`is restricted to the range, 0 <`beta`< 1. The default value is`beta`= 1/2. Values close to 0 give all data equal weighting. Increasing values of`beta`reduce the influence of outlying data. Values close to unity may cause instability or rank deficiency.The fitted spline is returned as a piecewise polynomial,

`pp`, and may be evaluated using`ppval`

.The splines are constructed of polynomials with degree

`order`. The default is a cubic,`order`=3. A spline with P pieces has P+`order`degrees of freedom. With periodic boundary conditions the degrees of freedom are reduced to P.The optional property,

`constaints`, is a structure specifying linear constraints on the fit. The structure has three fields,`"xc"`

,`"yc"`

, and`"cc"`

.`"xc"`

Vector of the x-locations of the constraints.

`"yc"`

Constraining values at the locations

`xc`. The default is an array of zeros.`"cc"`

Coefficients (matrix). The default is an array of ones. The number of rows is limited to the order of the piecewise polynomials,

`order`.

Constraints are linear combinations of derivatives of order 0 to

`order`-1 according tocc(1,j) * y(xc(j)) + cc(2,j) * y'(xc(j)) + ... = yc(:,...,:,j).

**See also:**interp1, unmkpp, ppval, spline, pchip, ppder, ppint, ppjumps.

The number of `breaks` (or knots) used to construct the piecewise
polynomial is a significant factor in suppressing the noise present in
the input data, `x` and `y`. This is demonstrated by the example
below.

x = 2 * pi * rand (1, 200); y = sin (x) + sin (2 * x) + 0.2 * randn (size (x)); ## Uniform breaks breaks = linspace (0, 2 * pi, 41); % 41 breaks, 40 pieces pp1 = splinefit (x, y, breaks); ## Breaks interpolated from data pp2 = splinefit (x, y, 10); % 11 breaks, 10 pieces ## Plot xx = linspace (0, 2 * pi, 400); y1 = ppval (pp1, xx); y2 = ppval (pp2, xx); plot (x, y, ".", xx, [y1; y2]) axis tight ylim auto legend ({"data", "41 breaks, 40 pieces", "11 breaks, 10 pieces"})

The result of which can be seen in Figure 28.1.

The piecewise polynomial fit, provided by `splinefit`

, has
continuous derivatives up to the `order`-1. For example, a cubic fit
has continuous first and second derivatives. This is demonstrated by
the code

## Data (200 points) x = 2 * pi * rand (1, 200); y = sin (x) + sin (2 * x) + 0.1 * randn (size (x)); ## Piecewise constant pp1 = splinefit (x, y, 8, "order", 0); ## Piecewise linear pp2 = splinefit (x, y, 8, "order", 1); ## Piecewise quadratic pp3 = splinefit (x, y, 8, "order", 2); ## Piecewise cubic pp4 = splinefit (x, y, 8, "order", 3); ## Piecewise quartic pp5 = splinefit (x, y, 8, "order", 4); ## Plot xx = linspace (0, 2 * pi, 400); y1 = ppval (pp1, xx); y2 = ppval (pp2, xx); y3 = ppval (pp3, xx); y4 = ppval (pp4, xx); y5 = ppval (pp5, xx); plot (x, y, ".", xx, [y1; y2; y3; y4; y5]) axis tight ylim auto legend ({"data", "order 0", "order 1", "order 2", "order 3", "order 4"})

The result of which can be seen in Figure 28.2.

When the underlying function to provide a fit to is periodic, `splinefit`

is able to apply the boundary conditions needed to manifest a periodic fit.
This is demonstrated by the code below.

## Data (100 points) x = 2 * pi * [0, (rand (1, 98)), 1]; y = sin (x) - cos (2 * x) + 0.2 * randn (size (x)); ## No constraints pp1 = splinefit (x, y, 10, "order", 5); ## Periodic boundaries pp2 = splinefit (x, y, 10, "order", 5, "periodic", true); ## Plot xx = linspace (0, 2 * pi, 400); y1 = ppval (pp1, xx); y2 = ppval (pp2, xx); plot (x, y, ".", xx, [y1; y2]) axis tight ylim auto legend ({"data", "no constraints", "periodic"})

The result of which can be seen in Figure 28.3.

More complex constraints may be added as well. For example, the code below illustrates a periodic fit with values that have been clamped at the endpoints, and a second periodic fit which is hinged at the endpoints.

## Data (200 points) x = 2 * pi * rand (1, 200); y = sin (2 * x) + 0.1 * randn (size (x)); ## Breaks breaks = linspace (0, 2 * pi, 10); ## Clamped endpoints, y = y' = 0 xc = [0, 0, 2*pi, 2*pi]; cc = [(eye (2)), (eye (2))]; con = struct ("xc", xc, "cc", cc); pp1 = splinefit (x, y, breaks, "constraints", con); ## Hinged periodic endpoints, y = 0 con = struct ("xc", 0); pp2 = splinefit (x, y, breaks, "constraints", con, "periodic", true); ## Plot xx = linspace (0, 2 * pi, 400); y1 = ppval (pp1, xx); y2 = ppval (pp2, xx); plot (x, y, ".", xx, [y1; y2]) axis tight ylim auto legend ({"data", "clamped", "hinged periodic"})

The result of which can be seen in Figure 28.4.

The `splinefit`

function also provides the convenience of a `robust`
fitting, where the effect of outlying data is reduced. In the example below,
three different fits are provided. Two with differing levels of outlier
suppression and a third illustrating the non-robust solution.

## Data x = linspace (0, 2*pi, 200); y = sin (x) + sin (2 * x) + 0.05 * randn (size (x)); ## Add outliers x = [x, linspace(0,2*pi,60)]; y = [y, -ones(1,60)]; ## Fit splines with hinged conditions con = struct ("xc", [0, 2*pi]); ## Robust fitting, beta = 0.25 pp1 = splinefit (x, y, 8, "constraints", con, "beta", 0.25); ## Robust fitting, beta = 0.75 pp2 = splinefit (x, y, 8, "constraints", con, "beta", 0.75); ## No robust fitting pp3 = splinefit (x, y, 8, "constraints", con); ## Plot xx = linspace (0, 2*pi, 400); y1 = ppval (pp1, xx); y2 = ppval (pp2, xx); y3 = ppval (pp3, xx); plot (x, y, ".", xx, [y1; y2; y3]) legend ({"data with outliers","robust, beta = 0.25", ... "robust, beta = 0.75", "no robust fitting"}) axis tight ylim auto

The result of which can be seen in Figure 28.5.

The function, `ppval`

, evaluates the piecewise polynomials, created
by `mkpp`

or other means, and `unmkpp`

returns detailed
information about the piecewise polynomial.

The following example shows how to combine two linear functions and a quadratic into one function. Each of these functions is expressed on adjoined intervals.

x = [-2, -1, 1, 2]; p = [ 0, 1, 0; 1, -2, 1; 0, -1, 1 ]; pp = mkpp (x, p); xi = linspace (-2, 2, 50); yi = ppval (pp, xi); plot (xi, yi);

- Function File:
`pp`=**mkpp***(*`breaks`,`coefs`) - Function File:
`pp`=**mkpp***(*`breaks`,`coefs`,`d`) -
Construct a piecewise polynomial (pp) structure from sample points

`breaks`and coefficients`coefs`.`breaks`must be a vector of strictly increasing values. The number of intervals is given by

.`ni`= length (`breaks`) - 1When

`m`is the polynomial order`coefs`must be of size:`ni`x`m`+ 1.The i-th row of

`coefs`,

, contains the coefficients for the polynomial over the`coefs`(`i`,:)`i`-th interval, ordered from highest (`m`) to lowest (`0`).`coefs`may also be a multi-dimensional array, specifying a vector-valued or array-valued polynomial. In that case the polynomial order is defined by the length of the last dimension of`coefs`. The size of first dimension(s) are given by the scalar or vector`d`. If`d`is not given it is set to`1`

. In any case`coefs`is reshaped to a 2-D matrix of size`[`

`ni`*prod(`d``m`)]**See also:**unmkpp, ppval, spline, pchip, ppder, ppint, ppjumps.

- Function File:
*[*`x`,`p`,`n`,`k`,`d`] =**unmkpp***(*`pp`) -
Extract the components of a piecewise polynomial structure

`pp`.The components are:

`x`Sample points.

`p`Polynomial coefficients for points in sample interval.

contains the coefficients for the polynomial over interval`p`(`i`, :)`i`ordered from highest to lowest. If

,`d`> 1

contains the coefficients for the r-th polynomial defined on interval`p`(`r`,`i`, :)`i`.`n`Number of polynomial pieces.

`k`Order of the polynomial plus 1.

`d`Number of polynomials defined for each interval.

- Function File:
`yi`=**ppval***(*`pp`,`xi`) Evaluate the piecewise polynomial structure

`pp`at the points`xi`.If

`pp`describes a scalar polynomial function, the result is an array of the same shape as`xi`. Otherwise, the size of the result is`[pp.dim, length(`

if`xi`)]`xi`is a vector, or`[pp.dim, size(`

if it is a multi-dimensional array.`xi`)]

- Function File:
*ppd =***ppder***(pp)* - Function File:
*ppd =***ppder***(pp, m)* Compute the piecewise

`m`-th derivative of a piecewise polynomial struct`pp`.If

`m`is omitted the first derivative is calculated.

- Function File:
`ppi`=**ppint***(*`pp`) - Function File:
`ppi`=**ppint***(*`pp`,`c`) Compute the integral of the piecewise polynomial struct

`pp`.`c`, if given, is the constant of integration.

- Function File:
`jumps`=**ppjumps***(*`pp`) Evaluate the boundary jumps of a piecewise polynomial.

If there are

*n*intervals, and the dimensionality of`pp`is*d*, the resulting array has dimensions`[d, n-1]`

.**See also:**mkpp.