0
votes

I have a set of x and y values that I would like to fit a polynomial curve around. The function should take the form of up to a 9th order polynomial;

y = a(1)*X.^1 + a(2)*X.^2 + a(3)*X.^3 + a(4)*X.^4 + a(5)*X.^5 + a(6)*X.^6 + a(7)*X.^7 + a(8)*X.^8 + a(9)*X.^9;

where a(n) are my coefficients.

There are two issues I have. This curve might not always take the form of a 9th order polynomial. It may be a 3rd order, 6th order or whatever (UP TO max 9th order).

I am unsure how to set this up using the optimisation toolbox. Any ideas?

Secondly, can I set a constraint so that the calculated y values are always postive?

Many thanks,

Current code below.

Function;

function F = polyfun(a,redCO2)
F = a(1)*redCO2.^1 + a(2)*redCO2.^2 + a(3)*redCO2.^3 + a(4)*redCO2.^4 + a(5)*redCO2.^5 + a(6)*redCO2.^6 + a(7)*redCO2.^7 + a(8)*redCO2.^8 + a(9)*redCO2.^9;

F = @(a) polyfun(a,X);

a0 = [100, 100, 100, 100, 100, 100, 100, 100, 100]; % Starting guess

a = lsqcurvefit(@polyfun,a0,X,y);
2
Apologies, function code should read X where it says redCO2 - user3491279
If you have access to it, the curve fitting toolbox would probably be a better tool to use for what you're trying to do. - MrAzzaman

2 Answers

2
votes

You have two separate requests.

For the unconstrained fit, you don't need any function at all, the problem is linear and mrdivide and/or pinv gives the best fit in the least-squares sense:

a = y / bsxfun(@power, x, 1:9);

or

a = y * pinv(bsxfun(@power, x, 1:9));

If the system is underconstrained, one of these will give a "small" solution in the l2-norm sense, the other in the l0-norm sense. If the system is fully or over constrained, they'll both give the value of a that minimizes the integral-square error (l2-norm).

For a constrained fit, the lsqcurvefit function you've already discovered works well. Just set the lb argument to a vector of zeros to force a to be non-neqgative:

a = lsqcurvefit(@polyval,a0,X,y,zeros(1,9));
1
votes

Just use polyfit, that's precisely what it's designed for:

% Data you want to fit in x and y
% n is the polynomial order of your choosing
% the polynomial coefficients are returned in the vector p
p = polyfit(x,y,n);

You can then use polyval to evaluate the polynomial p over a vector of x values.