MATLAB: Curve fitting tool with custom equation, odd power polynomial

Curve Fitting Toolboxcustom equationodd power polynomial fitpolynomial fit

I am trying to fit an odd power polynomial of the form (f(x) = p1*x^3 + p3*x) to a data set of with 38 points, which clearly shows a smooth cubic polynomial. I am using the custom equation type in the curve fitting tool to do this. I understand the custom fit is sensitive to the starting parameters, so I first run the standard 3rd order polynomial fit to my data. The fit includes even power terms, but I extract the odd order coefficients and use those as a starting point in my custom fit. It does not work well at all.
As a test, I plugged in the full 3rd order polynomial equation into the custom equation (i.e. f(x) = p1*x^3 + p2*x^2 + p3*x + p4), and set my starting values to the same order of magnitude solved for in the standard polynomial fit, and the custom equation fit still did not fit well at all. How do I fix this?
Alternatively, how can I best fit an odd power polynomial?

Best Answer

It seems like overkill to use the curve fit toolbox just to fit a 1D polynomial. And it should not depend on any starting parameter guess. For a polynomial fit, the coefficients should be the unique solution to a set of linear equations. Below is what I use. For you, the usage would be,
>> polyfitc(x,y,[3 1])
function p=polyfitc(x,y,nvec)
%Simple 1D polynomial fitting with particular coefficients constrained to
%zero
%




% p=polyfitc(x,y,nvec)
%
%in:
%
% nvec: A vector of integer exponents present in the polynomial.
% x: x data
% y: y data
%
%out:
%
% p: vector of polynomial coefficients. Order of polynomial is max(nvec).
A=bsxfun(@power,x(:),nvec(:).');
[QQ,RR]=qr(A,0);
coeffs = RR\( QQ'*y(:) );
p=zeros(1,max(nvec)+1);
p(nvec+1)=coeffs;
p=p(end:-1:1);