How to fit a Gaussian curve by code?
24 views (last 30 days)
Show older comments
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 Comment
Answers (1)
Matt J
on 11 Apr 2022
Edited: Matt J
on 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,[],[]});
[A,mu,sig2]=deal(params{2:4})%parameters
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')
See Also
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
