fit curve and equation with a constant coefficient

11 visualizzazioni (ultimi 30 giorni)
Hello,
I have an equation to fit with the data. I get a good fit.
yfit=(a+ (b./x.^2)).*exp(-x/c);
I get the a,b and c numbers. However, I need to include a constant coefficient into the equation
ConstantCoeff=1e17;
yfit=ConstantCoeff(a+ (b./x.^2)).*exp(-x/c); then the fit is pretty off and I get the same a,b and c numbers.
What it does is it fits the curve first and shift the curve with the amount of coeff. I don't want that. I would like to calculate the a,b and c when the constant coefficient is there.
[a,b,c]=deal(3,2,1);
x=linspace(1,2,30);
y=(a+(b./x.^2)).*exp(-x/c);
funlist={1,@(c,x) exp(-x/c)./x.^2};
[c,ab]=fminspleas(funlist,2, x,y);
a=ab(1), b=ab(2),c %fitted values
%yfit=(a+ (b./x.^2)).*exp(-x/c); %no coeff
ConstantCoeff=1e17;
yfit=ConstantCoeff*(a+ (b./x.^2)).*exp(-x/c); %with coeff
plot(x,y,'x',x,yfit); legend('Sample Data','Fit')
set(gca, 'YScale', 'log')

Risposte (1)

Akshat
Akshat il 22 Set 2023
Hi Birsen,
As per my understanding of the question, the constants a, b and c should have different values along with the coefficient than it is having now.
I also tried to run your code on my end, but it was throwing errors, and hence I tried to write the new code as per my understanding.
The only major change I made in my code is that I used “lsqcurvefit” to fit the function instead of “fminspleas” as it was throwing an error for me.
After that, I just fitted the curve and extracted the values in variables “a_fit”,b_fit” and “c_fit”. Then I calculated the curve according to these new constants and plotted the result, I got the following result:
The code I used is:
[a, b, c] = deal(3, 2, 1);
x = linspace(1, 2, 30);
y = (a + (b ./ x.^2)) .* exp(-x / c);
ConstantCoeff = 1e17;
% Define the function to fit
fun = @(ab, x) ab(4) * (ab(1) + (ab(2) ./ x.^2)) .* exp(-x / ab(3));
% Initial parameter guess
ab0 = [a, b, c, ConstantCoeff];
% Perform the curve fitting
ab_fit = lsqcurvefit(fun, ab0, x, y);
% Extract the fitted parameters
a_fit = ab_fit(1);
b_fit = ab_fit(2);
c_fit = ab_fit(3);
ConstantCoeff_fit = ab_fit(4);
% Calculate the fitted curve
yfit = ConstantCoeff_fit * (a_fit + (b_fit ./ x.^2)) .* exp(-x / c_fit);
plot(x, y, 'x', x, yfit);
legend('Sample Data', 'Fit');
set(gca, 'YScale', 'log');
You can refer to the “lsqcurvefit” documentation here https://www.mathworks.com/help/optim/ug/lsqcurvefit.html
Hope this helps!

Prodotti


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by