polyfitIn the following discussion,
to minimise the sum of squared errors (SSE)
where
and the vectors
To fit an
In this app, the least-square problem is solved by QR decomposition, as we will show in the following.
For convenience, let
where
where
where
We divide
where
This can be minimized by selecting
In this case,
For convenience, let
is one of the many solutions to the least-square problem.
In this case,
is one of the many solutions to the least-square problem.
For convenience, let
is one of the many solutions to the least-square problem.
| Full rank | Rank deficient | |
|---|---|---|
| Overdetermined system, i.e., | The polynomial fitting problem has many solutions, where | |
| Underdetermined system, i.e., | The polynomial fitting problem has many solutions, where p passes through all of the data points. | The polynomial fitting problem has many solutions, where |
p = polyfit(x,y,n)x and y should be arrays that contain the Inf nor NaN.x or y is not a vector, it will be reshaped to a vector.x and y should be non-empty and have the same lengths.n should be a real non-negative integer, representing the order of the polynomial.p contains coefficients of the polynomial that is a best fit of the given data points. That means, p minimises the sum of squared errors (SSE) discussed here. The first element of p corresponds to the highest order term.x or y is complex, p will be complex.[p,S] = polyfit(x,y,n)x, y, n and p are as described in p = polyfit(x,y,n) above.
S is a structure that can be used in polyval to evaluate standard errors of prediction. S should contain the following fields:
[p,S,mu] = polyfit(x,y,n)x, y, n and p are as described in p = polyfit(x,y,n) above.S is as described in [p,S] = polyfit(x,y,n) above.mu is a vector of 2 elements where mu(1) and mu(2) are the mean and standard deviation of x, respectively. It fits a polynomial to data points with (x-mu(1)) / mu(2) and y, respectively.x has only one element, mu is [x, 0] and the given data point will not be transformed.polyfit is clear
% Data points.
x=linspace(0,2);
y=x.^2+normrnd(0,0.2,[1 length(x)]);
% Get polynomial of degree 2 that fits the data.
p=polyfit(x,y,2)
scatter(x,y)
hold('on')
% Plot the polynomial
xx=0:0.01:2;
yy=polyval(p,xx);
plot(xx,yy)
hold('off')
All variables cleared.
p = 1e-1 ×
9.9945 -0.0455 0.1359
clear
% Data points.
% y is constant.
x=1:5;
y=rand*ones(1,length(x));
% Get polynomial of degree 3 that fits the data.
% It returns a zero-th degree polynomial because the y-data are constant.
[p,S]=polyfit(x,y,3)
scatter(x,y)
hold('on')
% Plot the polynomial
xx=0:0.01:5;
yy=polyval(p,xx);
plot(xx,yy)
ylim([0 1])
ylabel('y')
xlabel('x')
hold('off')
All variables cleared.
p = 1e-1 ×
-0.0000 0.0000 -0.0000 3.9839
S =
struct with fields:
df: [1.0000]
R: Double [4 x 4]
normr: [3.3766] × 1e-16