How to fit a Gaussian curve by code?

21 ビュー (過去 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')
  1 件のコメント
Torsten
Torsten 2022 年 4 月 11 日
:-)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet 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