How to fit a Gaussian curve by code?

160 visualizzazioni (ultimi 30 giorni)
Vivian Yu
Vivian Yu il 11 Apr 2022
Commentato: Torsten il 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 Commento
Torsten
Torsten il 11 Apr 2022
Modificato: Torsten il 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.

Accedi per commentare.

Risposte (1)

Matt J
Matt J il 11 Apr 2022
Modificato: Matt J il 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')

Categorie

Scopri di più su Get Started with Curve Fitting Toolbox in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by