MATLAB curve fitting - least squares method - wrong "fit" using high degrees -
anyone here me following problem? following code calculates best polynomial fit given data-set, is; polynomial of specified degree.
unfortunately, whatever data-set may be, @ degree 6 or higher, matlab gets totally wrong fit. fit curves totally away data in sort of exponantial-looking-manner downwards. (see example: degree = 8).
x=[1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5] % experimental x-values y=[4.3 6.2 10.1 13.5 19.8 22.6 24.7 29.2] % experimental y-values degree=8; % specify degree = zeros(length(x),degree); exponent=0:degree; data=1:length(x); a(data,exponent+1)=x(data).^exponent; % create matrix end; end; a=inv((transpose(a)*a))*transpose(a)*y'; % coƫfficients of polynom a=flipud(a); fitpolynoom=polyval(a,x); error=sum((y-fitpolynoom).^2); % calculates fit-error using least-squares method fitpolynoom=polyval(a,x); figure; plot(x,y,'black*',x,fitpolynoom,'g-'); error % displays value of fit-error in matlab command window
thanks in advance.
first, remarks: least-squares fitting polynomials in matlab, use existingpolyfit
function instead. furthermore (this may depend on application) should not fitting $8$th degree polynomials, when have $8$ data points. in answer, assume have reasons fit polynomials data (e.g., self-study purposes).
the issue numeric problem arising matrix inversion. solving equations of type $ax=b$ $a$ square matrix, inverting $a$ not recommended (see blogpost 'don't invert matrix' john d. cook). in least-squares case, instead of \begin{equation} = (a^\mathrm{t} a)^{-1} a^\mathrm{t} y^\mathrm{t} \end{equation} better solve \begin{equation} (a^\mathrm{t} a)a = a^\mathrm{t} y^\mathrm{t} \end{equation} other means. in matlab code, may replace
a=inv((transpose(a)*a))*transpose(a)*y';
by
a = (transpose(a) * a) \ (transpose(a) * y');
by modification code, obtained fit going through data points.
Comments
Post a Comment