MATLAB: How to use the formula extracted from a curve fitting algorithm

anonymous functioncurve fittingformulainline()

Hello everybody,
Actually I'm using the code generated by the curve fitting toolbox because it's an easy way for fit.
x = linspace(0,10,100);
y = sin(2*pi*10.*x);
plot(x,y)
[fitresult, gof, xData, yData] = createFit_sin(x, y);% call of the fitting function
fit=fitresult;
% extracting equation loop
eq = formula(fitresult); %Formula of fitted equation
parameters = coeffnames(fitresult); %All the parameter names
values = coeffvalues(fitresult); %All the parameter values
for idx = 1:numel(parameters)
param = parameters{idx};
l = length(param);
loc = regexp(eq, param); %Location of the parameter within the string
while ~isempty(loc)
eq = [eq(1:loc-1) num2str(values(idx)) eq(loc+l:end)];%Substitute parameter value
loc = regexp(eq, param);
end
end
eq
function [fitresult, gof, xData, yData] = createFit_sin(x, y)
%%Fit: 'untitled fit 1'.
[xData, yData] = prepareCurveData( x, y );
% Set up fittype and options.
ft = fittype( 'sin1' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.Lower = [-Inf 0 -Inf];
opts.StartPoint = [1 0.628318530717959 -1.16676298065496e-14];
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );
end
Normally if you take a look over the "eq" variable the loop that I'm using extract me the formula and the coefficient values, and the problem is how to use this equation i have tried it with "anonymous function", "inline" but I do not succeed to use it properly because the expression "eq" is converted to char and I don't succed to holding it. I'm already using it through the use of the coefficient but i have to write the equation for each fit, it might be some way to make it simplier.
Thanks in advance.

Best Answer

It's not clear to me why you can't just use the returned fit structure for whatever it is that you needs must want to do, but to create an anonymous function handle from the equation, use something similar to
>> ft=fit([1:10]',[linspace(0,10,10)]','poly1');
>> str2func(['@(x)' formula(ft)])
ans =
@(x)p1*x+p2
>>
NB: the prefixing of the returned formula string with the handle and dummy argument list is required in recent releases of Matlab--early versions would try to impute that from the string but that feature now errors.
NB2: do NOT use eq for a variable name; that aliases the builtin name for the '==' operator which could wreak havoc elsewhere in code if were need for it. Something like eqn would be short, meaningful abbreviation and not conflict.