MATLAB: How to create ‘fittype’ objects of polynomial degree exceeding 5

Curve Fitting Toolbox

'fittype' only allows to create objects up to polynomial order five (poly55). How can I generate fits in x and y for higher-degree polynomials?

Best Answer

Below is a function which allows to generate 'fittype' objects for polynomials in x and y of arbitrary degree n.
function out=generatefittype(n)
M=unique(nchoosek(repmat(0:n,1,2),2),'rows');
M=fliplr(M(sum(M,2)<=n,:));
[~,ind]=sort(sum(M,2),'ascend');
M=M(ind,:);
digits = numel(num2str(n));
formatStr= ['p%0',num2str(digits),'d%0',num2str(digits),'d\n'];
coeffs=strsplit(sprintf(formatStr,M'));
tmp = strsplit(regexprep(sprintf('x^%d*y^%d\n',M'),'(x\^0\*y\^0)|(x\^0\*)|(y\^0\*)|(\*y\^0)',''),'\n');
out=fittype([{'1'},tmp(2:end-1)],'independent',{'x','y'},'dependent','z','coefficients',coeffs(1:end-1));
end