问题
I'm fitting custom functions to my data. After obtaining the fit I would like to get something like a function handle of my fit function including the parameters set to the ones found by the fit. I know I can get the model with
formula(fit)
and I can get the parameters with
coeffvalues(fit)
but is there any easy way to combine the two in one step?
回答1:
This little loop will do the trick:
x = (1:100).'; %'
y = 1*x.^5 + 2*x.^4 + 3*x.^3 + 4*x.^2 + 5*x + 6;
fitobject = fit(x,y,'poly5');
cvalues = coeffvalues(fitobject);
cnames = coeffnames(fitobject);
output = formula(fitobject);
for ii=1:1:numel(cvalues)
cname = cnames{ii};
cvalue = num2str(cvalues(ii));
output = strrep(output, cname , cvalue);
end
output = 1*x^5 + 2*x^4 + 3*x^3 + 4*x^2 + 5*x + 6
The loop needs to be adapted to the number of coefficients of your fit.
Edit: two slight changes in order to fully answer the question.
fhandle = @(x) eval(output)
returns a function handle. Secondly output as given by your procedure doesn't work, as the power operation reads .^ instead of x, which can obviously be replaced by
strrep(output, '^', '.^');
回答2:
You can use the Matlab curve fitting function, polyfit
.
p = polyfit(x,y,n)
So, p
contains the coefficients of the polynomial, x
and y
are the coordinates of the function you're trying to fit. n
is the order of the polynomial. For example, n=1
is linear, n=2
is quadratic, etc. For more info, see this documentation centre link. The only issue is that you may not want a polynomial fit, in which case you'll have to use different method.
Oh, and you can use the calculated coefficients p
to to re-evaluate the polynomial with:
f = polyval(p,x);
Here, f
is the value of the polynomial with coefficients p
evaluated at points x
.
来源:https://stackoverflow.com/questions/16478077/get-function-handle-of-fit-function-in-matlab-and-assign-fit-parameters