Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiating a Centred and Scaled Polyfit Fit

I have some data which I wish to model in order to be able to get relatively accurate values in the same range as the data.

To do this I used polyfit to fit a 6th order polynomial and due to my x-axis values it suggested I centred and scaled it to get a more accurate fit which I did.

However, now I want to find the derivative of this function in order to model the velocity of my model.

But I am not sure how the polyder function interacts with the scaled and fitted polyfit which I have produced. (I don't want to use the unscaled model as this is not very accurate).

Here is some code which reproduces my problem. I attempted to rescale the x values before putting them into the fit for the derivative but this still did no fix the problem.

x = 0:100;
y = 2*x.^2 + x + 1;

Fit = polyfit(x,y,2);

[ScaledFit,s,mu] = polyfit(x,y,2);

Deriv = polyder(Fit);
ScaledDeriv = polyder(ScaledFit);

plot(x,polyval(Deriv,x),'b.');
hold on
plot(x,polyval(ScaledDeriv,(x-mu(1))/mu(2)),'r.');

Here I have chosen a simple polynomial so that I could fit it accurate and produce the actual derivative.

Any help would be greatly appreciated thanks. I am using Matlab R2014a BTW.

Edit. Just been playing about with it and by dividing the resulting points for the differential by the standard deviation mu(2) it gave a very close result within the range -3e-13 to about 5e-13.

polyval(ScaledDeriv,(x-mu(1))/mu(2))/mu(2);

Not sure quite why this is the case, is there another more elegant way to solve this?

Edit2. Sorry for another edit but again was mucking around and found that for a large sample x = 1:1000; the deviation became much bigger up to 10. I am not sure if this is due to a bad polyfit even though it is centred and scaled or due to the funny way the derivative is plotted.

Thanks for your time

like image 326
Malrig Avatar asked Aug 08 '14 15:08

Malrig


1 Answers

A simple application of the chain rule gives

df(x)/dx = df(xS)/dxS * dxS/dx

Since by definition

xS = (x-mu1)/mu2

it follows that

df(x)/dx = df(xS)/dxS /mu2

Which is exactly what you have verified numerically.

The lack of accuracy for large samples is due to the global, rather then local, Lagrange polynomial interpolation which you have done. I would suggest that you try to fit your data with splines, and obtain the derivative with fnder(). Another option is to apply the polyfit() function locally, i.e. to a moving small set of points, and then apply polyder() to all the fitted polynomials.

like image 196
Jommy Avatar answered Nov 09 '22 11:11

Jommy