豆粑粑 fit Gaussian matlab
本帖最后由 meatball1982 于 2019-1-25 16:40 编辑matlab fit Gaussian distribution
init parameter is max, std andmean of y.
the both of the lsqcurvefit and nlinfit are applied to iterative
fun_fit_gau.m
function =fun_fit_gau(x,y)
b(1)=max(y);
b(2)= std(y);
b(3)=mean(y);
fx=@(b,x)b(1)*exp(-b(2)*(x-b(3)).^2);
for l=1:3
b=lsqcurvefit(fx,b,x,y);
b=nlinfit(x,y,fx,b);
end
x_new=interp1(,x,);
y_new = b(1)*exp(-b(2)*(x_new-b(3)).^2);
main.m
clear all
clc
clf
%% outline
%
%% main
dat1 = load('../data/deltE_QM1.dat');
hi_bi = linspace(-20,5,26);
=hist(dat1(:,2),hi_bi);
hi_va1=hi_va1./sum(hi_va1);
=fun_fit_gau(hi_bi,hi_va1);
pl_max = 1.2*max(hi_va1);
subplot(2,2,1)
hold on
plot(dat1(:,1),dat1(:,2),'m-','linewidth',1.5)
grid on
box on
axis()
title('data')
subplot(2,2,2)
hold on
barh(hi_bi,hi_va1,'m')
axis()
grid on
box on
title('hist')
subplot(2,2,3)
hold on
plot(hi_bi,hi_va1,'mo')
plot(hi_bi1_new,hi_va1_new,'r-','linewidth',2)
box on
grid on
axis([-20 5 0 pl_max])
title('Gau fit')
h=gcf;
fi_na='../file_imgs/fig_gau_1dat';
fun_work_li_035_myfig_out(h,fi_na,3);
一个较新的版本
function =fun_mm_fit_1Gau(x,y)
%%
%
% =fun_mm_fit_1Gau(x,y)
%
% %--------------------------------------------------------------
% Inputs:
% x,y
% Outputs:
% Gau_fit : the Gaussian fit value of x
% Gau_par : the parameters in
% b(1)*exp(-b(2)*(x-b(3)).^2)+b(4)
% x_fit : more x points for a smoother line
% y_fit : more y points for a smoother line
% fx : the function to calculate the points users define
% % x_new = [ 1 3 17 30 40];
% % y_new = fx(Gau_par,x_new);
%
% %--------------------------------------------------------------
% example
% np = 1000;
% p = 10* randn(1,np)+3 +10;
% hi_bi = linspace(-40,60,50);
% hi_va = hist(p,hi_bi);
%
% x = hi_bi;
% y = hi_va;
% =fun_mm_fit_1Gau(x,y);
%
%
% x_new = [ 1.2 3.3 17.8 30.001 40.08];
% y_new = fx(Gau_par,x_new);
%
% hold on
% stairs(hi_bi,hi_va,'b-')
% plot(x,Gau_fit,'gs')
% plot(x_fit,y_fit,'k-','linewidth',2)
% plot(x_new,y_new,'ro','markersize',10)
%
% %--------------------------------------------------------------
% type by : mm
% contact me : meatball1982@163.com
% typed on : 01-Jun-2021 14:11:21
%% main
% define the original function
fx=@(b,x)b(1)*exp(-b(2)*(x-b(3)).^2)+b(4);
% point number
n_p = length(x);
% smooth version of y, for find the initial b(3) with one peak
y_sm = smooth(y,ceil(n_p/10)+1);
=findpeaks(y_sm);
% for lsq fit, there is value < 0.
y(y==0)=-0.001;
b= ones(1,4);
b(3)=x(pks_ind(1));
b(1)=max(y);
for i_ite=1:10
% Solve nonlinear curve-fitting problems in least-squares sense.
% just a guess.
b=lsqcurvefit(fx,b,x,y);
% Nonlinear regression,
b=nlinfit(x,y,fx,b);
end
% more points and smoother
x_fit = linspace(min(x),max(x),n_p*5);
y_fit = fx(b,x_fit);
y_fit(y_fit<0)=0;
% Fit points
Gau_fit = fx(b,x);
Gau_fit(Gau_fit<0)=0;
% parameters
Gau_par = b;
%% logs
% mod : 01-Jun-2021 13:24:37
%
页:
[1]