How to fit a Gaussian curve by code?

21 Ansichten (letzte 30 Tage)
Vivian Yu
Vivian Yu am 11 Apr. 2022
Kommentiert: Torsten am 11 Apr. 2022
Hi,
I want to fit a Gaussian curve by coding because I want to fit many type of 1-D data. I'm not using the "curve fitting" app.
However, when I write the code below, the result has something wrong.
I hope that the result should be the same as using "curve fitting" APP.
load('Gaussian.mat');
x0 = [0 0 0];
fitfunc = fittype('a.*exp(-((x-b)/c).^2)');
[fitted_curve,gof] = fit(x,y,fitfunc,'StartPoint',x0);
% Save the coeffiecient values for a,b,c and d in a vector
coeffvals = coeffvalues(fitted_curve);
% Plot results
figure(2)
plot(x,y,'r');
hold on
plot(x,fitted_curve(x),'k','LineWidth',1.5);
hold off
xlabel('Time');
ylabel('Voltage');
title('sinusoidal drive waveform & fitting curve');
set(gca,'fontsize',14);
  1 Kommentar
Torsten
Torsten am 11 Apr. 2022
Bearbeitet: Torsten am 11 Apr. 2022
Since your data look in no way like a Gaussian, I think the fit is the best MATLAB could do out of it.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Matt J
Matt J am 11 Apr. 2022
Bearbeitet: Matt J am 11 Apr. 2022
If we throw away the data values with y=0, then the remaining data fits a Gaussian quite well. I recommend downloading gaussfitn for the fit.
load Gaussian
keep=(y>0);
x=x(keep)/1e6;
y=y(keep);
[params,resid]=gaussfitn(x,y,{0,1,20,[]},{0,max(y),max(x)},{0,[],[]});
Local minimum possible. lsqcurvefit stopped because the final change in the sum of squares relative to its initial value is less than the value of the function tolerance.
[A,mu,sig2]=deal(params{2:4})%parameters
A = 2.9709e+04
mu = 19.9730
sig2 = 6.9382
fun=@(x) A*exp( -0.5 * (x-mu).^2./sig2);
%Plot the fit
h=plot(x,fun(x),'-',x(1:20:end),y(1:20:end),'o');
h(1).LineWidth=2;
xlabel x; ylabel y; legend('Fit','Data Samples')

Kategorien

Mehr zu Get Started with Curve Fitting Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by