How to fit a Gaussian curve by code?

조회 수: 28 (최근 30일)
Vivian Yu
Vivian Yu 2022년 4월 11일
댓글: Torsten 2022년 4월 11일
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
Torsten
Torsten 2022년 4월 11일
편집: Torsten 2022년 4월 11일
Since your data look in no way like a Gaussian, I think the fit is the best MATLAB could do out of it.

댓글을 달려면 로그인하십시오.

답변 (1개)

Matt J
Matt J 2022년 4월 11일
편집: Matt J 2022년 4월 11일
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')

카테고리

Help CenterFile Exchange에서 Get Started with Curve Fitting Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by