Saturday, 10 September 2011

Non-linear least squares fit forced through a point

Sometimes you want a least-squares polynomial fit to data but to constrain it so it passes through a certain point. Well ... Inputs: x, y (data); x0 and y0 are the coordinates of the point you want it to pass through, and n is the degree of polynomial
function [p,yhat] = lsq_fit_nonlin_force_thru_point(x,y,x0,y0,n);
x = x(:); %reshape the data into a column vector
y = y(:);
% 'C' is the Vandermonde matrix for 'x'
V(:,n+1) = ones(length(x),1,class(x));
for j = n:-1:1
V(:,j) = x.*V(:,j+1);
end
C = V;
% 'd' is the vector of target values, 'y'.
d = y;
%%
% There are no inequality constraints in this case, i.e.,
A = [];
b = [];
%%
% We use linear equality constraints to force the curve to hit the required point. In
% this case, 'Aeq' is the Vandermoonde matrix for 'x0'
Aeq = x0.^(n:-1:0);
% and 'beq' is the value the curve should take at that point
beq = y0;
%%
p = lsqlin( C, d, A, b, Aeq, beq );
%%
% We can then use POLYVAL to evaluate the fitted curve
yhat = polyval( p, linspace(0,max(x),100) );
view raw nonlinlstsq.m hosted with ❤ by GitHub

No comments: