# 曲线拟合——（1）高斯曲线

本文主要是上一篇文章的补充，主要针对常用正态分布曲线拟合，文中内容多有借鉴他人，最后一并给出链接。

$f(x) = \frac{1}{{\sqrt {2\pi } \sigma }}{e^{ - \frac{{{{(x - \mu )}^2}}}{{2{\sigma ^2}}}}}$

A-编程

clc;clear all;close all;
%generate the orignal data
mu = 0;
sig2 = 2;
A = 4;
x=-10:.1:10;
y=A/sqrt(2*pi*sig2)*exp(-(x-mu).^2/sig2/2)+.05*randn(1,length(x));
subplot 211
scatter(x,y,'k');grid on;

%%curve fitting
%1-Gauss distribution
p = polyfit(x,log(y),2);
sig2_est = -1/2/p(1);
mu_est = sig2*p(2);
A_est = exp(mu^2/2/sig2+p(3))*sqrt(2*pi*sig2);

%plot
subplot 212
scatter(x,y,'k');hold on;
grid on;
plot(x,A/sqrt(2*pi*sig2)*exp(-(x-mu_est).^2/2/sig2),'r--','linewidth',2);


B-自带函数

clc;clear all;close all;
%generate the orignal data
mu = 0;
sig2 = 2;
A = 4;
x=-10:.1:10;
y=A/sqrt(2*pi*sig2)*exp(-(x-mu).^2/sig2/2)+0.05*randn(1,length(x));
subplot 211
scatter(x,y,'k');grid on;

%%curve fitting
%1-Gauss distribution
f = fittype('a*exp(-((x-b)/c)^2)');
[cfun,gof] = fit(x(:),y(:),f);
yo = cfun.a*exp(-((x-cfun.b)/cfun.c).^2);
%plot
subplot 212
scatter(x,y,'k');hold on;
grid on;
plot(x,yo,'r--','linewidth',2);


clc;clear all;close all;
%generate the orignal data
mu = 3;
sig2 = 2;
A = 40;
xold=-10:.1:10;
yold=A/sqrt(2*pi*sig2)*exp(-(xold-mu).^2/sig2/2)+0.5*randn(1,length(xold));
subplot 211
scatter(xold,yold,'k');grid on;
%%curve fitting
%select data
x = [];y = [];
Th = 0.3;%Threshold
for n = 1:length(xold)
if yold(n)>max(yold)*Th;
x = [x,xold(n)];
y = [y,yold(n)];
end
end

%1-Gauss distribution
p = polyfit(x,log(y),2);
sig2_est = -1/2/p(1);
mu_est = sig2*p(2);
A_est = exp(mu^2/2/sig2+p(3))*sqrt(2*pi*sig2);

%plot
subplot 212
scatter(xold,yold,'k');hold on;
grid on;
plot(xold,A/sqrt(2*pi*sig2)*exp(-(xold-mu_est).^2/2/sig2),'r--','linewidth',2);


posted @ 2017-03-15 20:53  桂。  阅读(30291)  评论(0编辑  收藏  举报