信号峰拟合的MATLAB程序,包括高斯拟合,多高斯拟合等多种类型

今天准备弄双高斯拟合,看到一个信号峰拟合的MATLAB版本的程序,大体看了一下,很不错,先MARK一下,以后再详细研究。

 http://terpconnect.umd.edu/~toh/spectrum/CurveFittingC.html
http://terpconnect.umd.edu/~toh/spectrum/InteractivePeakFitter.htm  
下面是其CODE。感叹别人的代码写的那个结构可扩展性,牛人啊!先来看他的一个双高斯拟合示例:


下面是MATLAB峰拟合函数:

  1. function [FitResults,LowestError,BestStart,xi,yi]=peakfit(signal,center,window,NumPeaks,peakshape,extra,NumTrials,start,AUTOZERO)  
  2. % Version 2.2: October, 2011. Adds exponential pulse and sigmoid models  
  3. % A command-line peak fitting program for time-series signals,   
  4. % written as a self-contained Matlab function in a single m-file.   
  5. % Uses an non-linear optimization algorithm to decompose a complex,   
  6. % overlapping-peak signal into its component parts. The objective  
  7. % is to determine whether your signal can be represented as the sum of  
  8. % fundamental underlying peaks shapes. Accepts signals of any length,  
  9. % including those with non-integer and non-uniform x-values. Fits   
  10. % Gaussian, equal-width Gaussians, exponentially-broadened Gaussian,   
  11. % Lorentzian, equal-width Lorentzians, Pearson, Logistic, exponential  
  12. % pulse, abd sigmoid shapes (expandable to other shapes). This is a command  
  13. % line version, usable from a remote terminal. It is capable of making   
  14. % multiple trial fits with sightly different starting values and taking  
  15. % the one with the lowest mean fit error.  Version 2.2: Sept, 2011.  
  16. %  
  17. % PEAKFIT(signal);         
  18. % Performs an iterative least-squares fit of a single Gaussian    
  19. % peak to the data matrix "signal", which has x values   
  20. % in column 1 and Y values in column 2 (e.g. [x y])  
  21. %  
  22. % PEAKFIT(signal,center,window);  
  23. % Fits a single Gaussian peak to a portion of the   
  24. % matrix "signal". The portion is centered on the   
  25. % x-value "center" and has width "window" (in x units).  
  26. %   
  27. % PEAKFIT(signal,center,window,NumPeaks);  
  28. % "NumPeaks" = number of peaks in the model (default is 1 if not  
  29. % specified).   
  30. %   
  31. % PEAKFIT(signal,center,window,NumPeaks,peakshape);  
  32. % Specifies the peak shape of the model: "peakshape" = 1-5.  
  33. % (1=Gaussian (default), 2=Lorentzian, 3=logistic, 4=Pearson,   
  34. % 5=exponentionally broadened Gaussian; 6=equal-width Gaussians;  
  35. % 7=Equal-width Lorentzians; 8=exponentionally broadened equal-width  
  36. % Gaussian, 9=exponential pulse, 10=sigmoid).  
  37. %  
  38. % PEAKFIT(signal,center,window,NumPeaks,peakshape,extra)  
  39. % Specifies the value of 'extra', used in the Pearson and the  
  40. % exponentionally broadened Gaussian shapes to fine-tune the peak shape.   
  41. %   
  42. % PEAKFIT(signal,center,window,NumPeaks,peakshape,extra,NumTrials);  
  43. % Performs "NumTrials" trial fits and selects the best one (with lowest  
  44. % fitting error). NumTrials can be any positive integer (default is 1).  
  45. %  
  46. % PEAKFIT(signal,center,window,NumPeaks,peakshape,extra,NumTrials,start)  
  47. % Specifies the first guesses vector "firstguess" for the peak positions  
  48. %  and widths, e.g. start=[position1 width1 position2 width2 ...]  
  49. %   
  50. % [FitResults,MeanFitError]=PEAKFIT(signal,center,window...)  
  51. % Returns the FitResults vector in the order peak number, peak  
  52. % position, peak height, peak width, and peak area), and the MeanFitError  
  53. % (the percent RMS difference between the data and the model in the  
  54. % selected segment of that data) of the best fit.  
  55. %  
  56. % Optional output parameters   
  57. % 1. FitResults: a table of model peak parameters, one row for each peak,  
  58. %    listing Peak number, Peak position, Height, Width, and Peak area.  
  59. % 2. LowestError: The rms fitting error of the best trial fit.  
  60. % 3. BestStart: the starting guesses that gave the best fit.  
  61. % 4. xi: vector containing 100 interploated x-values for the model peaks.   
  62. % 5. yi: matrix containing the y values of each model peak at each xi.   
  63. %    Type plot(xi,yi(1,:)) to plot peak 1 or plot(xi,yi) to plot all peaks  
  64. %  
  65. % T. C. O'Haver (toh@umd.edu). Version 2.2   
  66. %    
  67. % Example 1:   
  68. % >> x=[0:.1:10]';y=exp(-(x-5).^2);peakfit([x y])  
  69. % Fits exp(-x)^2 with a single Gaussian peak model.  
  70. %  
  71. %        Peak number  Peak position   Height     Width      Peak area  
  72. %             1            5            1        1.665       1.7725  
  73. %  
  74. % Example 2:  
  75. % x=[0:.1:10]';y=exp(-(x-5).^2)+.1*randn(size(x));peakfit([x y])  
  76. % Like Example 1, except that random noise is added to the y data.  
  77. % ans =  
  78. %             1         5.0279       0.9272      1.7948      1.7716  
  79. %  
  80. % Example 3:  
  81. % x=[0:.1:10];y=exp(-(x-5).^2)+.5*exp(-(x-3).^2)+.1*randn(size(x));  
  82. % peakfit([x' y'],5,19,2,1,0,1)  
  83. % Fits a noisy two-peak signal with a double Gaussian model (NumPeaks=2).  
  84. % ans =  
  85. %             1       3.0001      0.49489        1.642      0.86504  
  86. %             2       4.9927       1.0016       1.6597       1.7696  
  87. %  
  88. % Example 4:  
  89. % >> y=lorentzian(1:100,50,2);peakfit(y,50,100,1,2)  
  90. % Create and fit Lorentzian located at x=50, height=1, width=2.  
  91. % ans =  
  92. %            1           50      0.99974       1.9971       3.1079  
  93. % Example 5:   
  94. %   >> x=[0:.005:1];y=humps(x);peakfit([x' y'],.3,.7,1,4,3);  
  95. %   Fits a portion of the humps function, 0.7 units wide and centered on   
  96. %   x=0.3, with a single (NumPeaks=1) Pearson function (peakshape=4)  
  97. %   with extra=3 (controls shape of Pearson function).  
  98. %  
  99. % Example 6:   
  100. %  >> x=[0:.005:1];y=(humps(x)+humps(x-.13)).^3;smatrix=[x' y'];  
  101. %  >> [FitResults,MeanFitError]=peakfit(smatrix,.4,.7,2,1,0,10)  
  102. %  Creates a data matrix 'smatrix', fits a portion to a two-peak Gaussian  
  103. %  model, takes the best of 10 trials.  Returns FitResults and MeanFitError.  
  104. %  FitResults =  
  105. %              1      0.31056  2.0125e+006      0.11057  2.3689e+005  
  106. %              2      0.41529  2.2403e+006      0.12033  2.8696e+005  
  107. %  MeanFitError =  
  108. %         1.1899  
  109. %  
  110. % Example 7:  
  111. % >> peakfit([x' y'],.4,.7,2,1,0,10,[.3 .1 .5 .1]);  
  112. % As above, but specifies the first-guess position and width of the two  
  113. % peaks, in the order [position1 width1 position2 width2]  
  114. %  
  115. % Example 8:  
  116. % >> peakfit([x' y'],.4,.7,2,1,0,10,[.3 .1 .5 .1],0);  
  117. % As above, but sets AUTOZERO mode in the last argument.  
  118. % AUROZERO=0 does not subtract baseline from data segment.   
  119. % AUROZERO=1 (default) subtracts linear baseline from data segment.  
  120. % AUROZERO=2, subtracts quadratic baseline from data segment.  
  121. %  
  122. % For more details, see  
  123. % http://terpconnect.umd.edu/~toh/spectrum/CurveFittingC.html and  
  124. % http://terpconnect.umd.edu/~toh/spectrum/InteractivePeakFitter.htm  
  125. %  
  126. global AA xxx PEAKHEIGHTS  
  127.   
  128. format short g  
  129. format compact  
  130. warning off all  
  131.   
  132. datasize=size(signal);  
  133. if datasize(1)<datasize(2),signal=signal';end  
  134. datasize=size(signal);  
  135. if datasize(2)==1, %  Must be isignal(Y-vector)  
  136.     X=1:length(signal); % Create an independent variable vector  
  137.     Y=signal;  
  138. else  
  139.     % Must be isignal(DataMatrix)  
  140.     X=signal(:,1); % Split matrix argument   
  141.     Y=signal(:,2);  
  142. end  
  143. X=reshape(X,1,length(X)); % Adjust X and Y vector shape to 1 x n (rather than n x 1)  
  144. Y=reshape(Y,1,length(Y));  
  145. % If necessary, flip the data vectors so that X increases  
  146. if X(1)>X(length(X)),  
  147.     disp('X-axis flipped.')  
  148.     X=fliplr(X);  
  149.     Y=fliplr(Y);  
  150. end  
  151. % Y=Y-min(Y);  % Remove excess offset from data  
  152. % Isolate desired segment from data set for curve fitting  
  153. if nargin==1 || nargin==2,center=(max(X)-min(X))/2;window=max(X)-min(X);end  
  154. xoffset=center-window/2;  
  155. n1=val2ind(X,center-window/2);  
  156. n2=val2ind(X,center+window/2);  
  157. if window==0,n1=1;n2=length(X);end  
  158. xx=X(n1:n2)-xoffset;  
  159. yy=Y(n1:n2);  
  160. ShapeString='Gaussian';  
  161.   
  162. % Define values of any missing arguments  
  163. switch nargin  
  164.     case 1  
  165.         NumPeaks=1;  
  166.         peakshape=1;  
  167.         extra=0;  
  168.         NumTrials=1;  
  169.         xx=X;yy=Y;  
  170.         start=calcstart(xx,NumPeaks,xoffset);  
  171.         AUTOZERO=1;  
  172.     case 2  
  173.         NumPeaks=1;  
  174.         peakshape=1;  
  175.         extra=0;  
  176.         NumTrials=1;  
  177.         xx=signal;yy=center;  
  178.         start=calcstart(xx,NumPeaks,xoffset);  
  179.         AUTOZERO=1;  
  180.     case 3  
  181.         NumPeaks=1;  
  182.         peakshape=1;  
  183.         extra=0;  
  184.         NumTrials=1;  
  185.         start=calcstart(xx,NumPeaks,xoffset);  
  186.         AUTOZERO=1;  
  187.     case 4  
  188.         peakshape=1;  
  189.         extra=0;  
  190.         NumTrials=1;  
  191.         start=calcstart(xx,NumPeaks,xoffset);  
  192.         AUTOZERO=1;  
  193.     case 5  
  194.         extra=0;  
  195.         NumTrials=1;  
  196.         start=calcstart(xx,NumPeaks,xoffset);  
  197.         AUTOZERO=1;  
  198.     case 6  
  199.         NumTrials=1;  
  200.         start=calcstart(xx,NumPeaks,xoffset);  
  201.         AUTOZERO=1;  
  202.     case 7  
  203.         start=calcstart(xx,NumPeaks,xoffset);  
  204.         AUTOZERO=1;  
  205.     case 8  
  206.         AUTOZERO=1;  
  207.     otherwise  
  208. end % switch nargin  
  209.   
  210. % Remove baseline from data segment (alternative code)  
  211. % lxx=length(xx);  
  212. % bkgsize=10;  
  213. % if AUTOZERO==1,  % linear autozero operation    
  214. %     XX1=xx(1:round(lxx/bkgsize));  
  215. %     XX2=xx((lxx-round(lxx/bkgsize)):lxx);  
  216. %     Y1=yy(1:round(length(xx)/bkgsize));  
  217. %     Y2=yy((lxx-round(lxx/bkgsize)):lxx);  
  218. %     bkgcoef=polyfit([XX1,XX2],[Y1,Y2],1);  % Fit straight line to sub-group of points  
  219. %     bkg=polyval(bkgcoef,xx);  
  220. %     yy=yy-bkg;  
  221. % end % if  
  222.   
  223. % Remove baseline from data segment  
  224. X1=min(xx);X2=max(xx);Y1=min(Y);Y2=max(Y);  
  225. if AUTOZERO==1, % linear autozero operation    
  226.   Y1=mean(yy(1:length(xx)/20));  
  227.   Y2=mean(yy((length(xx)-length(xx)/20):length(xx)));  
  228.   yy=yy-((Y2-Y1)/(X2-X1)*(xx-X1)+Y1);  
  229. end % if  
  230.   
  231. if AUTOZERO==2, % Quadratic autozero operation    
  232.     XX1=xx(1:round(lxx/bkgsize));  
  233.     XX2=xx((lxx-round(lxx/bkgsize)):lxx);  
  234.     Y1=yy(1:round(length(xx)/bkgsize));  
  235.     Y2=yy((lxx-round(lxx/bkgsize)):lxx);  
  236.     bkgcoef=polyfit([XX1,XX2],[Y1,Y2],2);  % Fit parabola to sub-group of points  
  237.     bkg=polyval(bkgcoef,xx);  
  238.     yy=yy-bkg;  
  239. end % if autozero  
  240.   
  241. PEAKHEIGHTS=zeros(1,NumPeaks);  
  242. n=length(xx);  
  243. newstart=start;  
  244. switch NumPeaks  
  245.     case 1  
  246.         newstart(1)=start(1)-xoffset;  
  247.     case 2  
  248.         newstart(1)=start(1)-xoffset;  
  249.         newstart(3)=start(3)-xoffset;  
  250.     case 3  
  251.         newstart(1)=start(1)-xoffset;  
  252.         newstart(3)=start(3)-xoffset;  
  253.         newstart(5)=start(5)-xoffset;  
  254.     case 4  
  255.         newstart(1)=start(1)-xoffset;  
  256.         newstart(3)=start(3)-xoffset;  
  257.         newstart(5)=start(5)-xoffset;  
  258.         newstart(7)=start(7)-xoffset;  
  259.      case 5  
  260.         newstart(1)=start(1)-xoffset;  
  261.         newstart(3)=start(3)-xoffset;  
  262.         newstart(5)=start(5)-xoffset;  
  263.         newstart(7)=start(7)-xoffset;          
  264.         newstart(9)=start(9)-xoffset;  
  265.      case 6  
  266.         newstart(1)=start(1)-xoffset;  
  267.         newstart(3)=start(3)-xoffset;  
  268.         newstart(5)=start(5)-xoffset;  
  269.         newstart(7)=start(7)-xoffset;          
  270.         newstart(9)=start(9)-xoffset;  
  271.         newstart(11)=start(11)-xoffset;  
  272.     otherwise         
  273. end % switch NumPeaks  
  274.   
  275. % Perform peak fitting for selected peak shape using fminsearch function  
  276. options = optimset('TolX',.00001,'Display','off' );  
  277. LowestError=1000; % or any big number greater than largest error expected  
  278. FitParameters=zeros(1,NumPeaks.*2);   
  279. BestStart=zeros(1,NumPeaks.*2);   
  280. height=zeros(1,NumPeaks);   
  281. bestmodel=zeros(size(yy));  
  282. for k=1:NumTrials,   
  283.     % disp(['Trial number ' num2str(k) ] ) % optionally prints the current trial number as progress indicator  
  284.   switch peakshape  
  285.     case 1  
  286.         TrialParameters=fminsearch(@fitgaussian,newstart,options,xx,yy);  
  287.         ShapeString='Gaussian';  
  288.     case 2  
  289.         TrialParameters=fminsearch(@fitlorentzian,newstart,options,xx,yy);  
  290.         ShapeString='Lorentzian';      
  291.     case 3  
  292.         TrialParameters=fminsearch(@fitlogistic,newstart,options,xx,yy);  
  293.         ShapeString='Logistic';  
  294.     case 4  
  295.         TrialParameters=fminsearch(@fitpearson,newstart,options,xx,yy,extra);  
  296.         ShapeString='Pearson';  
  297.     case 5  
  298.         TrialParameters=fminsearch(@fitexpgaussian,newstart,options,xx,yy,-extra);  
  299.         ShapeString='ExpGaussian';  
  300.     case 6  
  301.         cwnewstart(1)=newstart(1);  
  302.         for pc=2:NumPeaks,  
  303.             cwnewstart(pc)=newstart(2.*pc-1);    
  304.         end  
  305.         cwnewstart(NumPeaks+1)=(max(xx)-min(xx))/5;  
  306.         TrialParameters=fminsearch(@fitewgaussian,cwnewstart,options,xx,yy);  
  307.         ShapeString='Equal width Gaussians';  
  308.     case 7  
  309.         cwnewstart(1)=newstart(1);  
  310.         for pc=2:NumPeaks,  
  311.             cwnewstart(pc)=newstart(2.*pc-1);    
  312.         end  
  313.         cwnewstart(NumPeaks+1)=(max(xx)-min(xx))/5;  
  314.         TrialParameters=fminsearch(@fitlorentziancw,cwnewstart,options,xx,yy);  
  315.         ShapeString='Equal width Lorentzians';  
  316.     case 8  
  317.         cwnewstart(1)=newstart(1);  
  318.         for pc=2:NumPeaks,  
  319.             cwnewstart(pc)=newstart(2.*pc-1);    
  320.         end  
  321.         cwnewstart(NumPeaks+1)=(max(xx)-min(xx))/5;  
  322.         TrialParameters=fminsearch(@fitexpewgaussian,cwnewstart,options,xx,yy,-extra);  
  323.         ShapeString='Exp. equal width Gaussians';  
  324.     case 9  
  325.         TrialParameters=fminsearch(@fitexppulse,newstart,options,xx,yy);  
  326.         ShapeString='Exponential Pulse';     
  327.     case 10  
  328.         TrialParameters=fminsearch(@fitsigmoid,newstart,options,xx,yy);  
  329.         ShapeString='Sigmoid';         
  330.       otherwise  
  331.   end % switch peakshape  
  332.     
  333. % Construct model from Trial parameters  
  334. A=zeros(NumPeaks,n);  
  335. for m=1:NumPeaks,  
  336.    switch peakshape  
  337.     case 1  
  338.         A(m,:)=gaussian(xx,TrialParameters(2*m-1),TrialParameters(2*m));  
  339.     case 2  
  340.         A(m,:)=lorentzian(xx,TrialParameters(2*m-1),TrialParameters(2*m));  
  341.     case 3  
  342.         A(m,:)=logistic(xx,TrialParameters(2*m-1),TrialParameters(2*m));  
  343.     case 4  
  344.         A(m,:)=pearson(xx,TrialParameters(2*m-1),TrialParameters(2*m),extra);  
  345.     case 5  
  346.         A(m,:)=expgaussian(xx,TrialParameters(2*m-1),TrialParameters(2*m),-extra)';  
  347.     case 6  
  348.         A(m,:)=gaussian(xx,TrialParameters(m),TrialParameters(NumPeaks+1));  
  349.     case 7  
  350.         A(m,:)=lorentzian(xx,TrialParameters(m),TrialParameters(NumPeaks+1));    
  351.     case 8  
  352.         A(m,:)=expgaussian(xx,TrialParameters(m),TrialParameters(NumPeaks+1),-extra)';      
  353.     case 9  
  354.         A(m,:)=exppulse(xx,TrialParameters(2*m-1),TrialParameters(2*m));    
  355.     case 10  
  356.         A(m,:)=sigmoid(xx,TrialParameters(2*m-1),TrialParameters(2*m));   
  357.        otherwise  
  358.   end % switch  
  359.       switch NumPeaks % adds random variation to non-linear parameters  
  360.        case 1  
  361.           newstart=[newstart(1)*(1+randn/50) newstart(2)*(1+randn/10)];   
  362.        case 2  
  363.           newstart=[newstart(1)*(1+randn/50) newstart(2)*(1+randn/10) newstart(3)*(1+randn/50) newstart(4)*(1+randn/10)];   
  364.        case 3  
  365.           newstart=[newstart(1)*(1+randn/50) newstart(2)*(1+randn/10) newstart(3)*(1+randn/50) newstart(4)*(1+randn/10) newstart(5)*(1+randn/50) newstart(6)*(1+randn/10)];   
  366.        case 4  
  367.           newstart=[newstart(1)*(1+randn/50) newstart(2)*(1+randn/10) newstart(3)*(1+randn/50) newstart(4)*(1+randn/10) newstart(5)*(1+randn/50) newstart(6)*(1+randn/10)  newstart(7)*(1+randn/50) newstart(8)*(1+randn/10)];   
  368.        case 5  
  369.           newstart=[newstart(1)*(1+randn/50) newstart(2)*(1+randn/10) newstart(3)*(1+randn/50) newstart(4)*(1+randn/10) newstart(5)*(1+randn/50) newstart(6)*(1+randn/10)  newstart(7)*(1+randn/50) newstart(8)*(1+randn/10)  newstart(9)*(1+randn/50) newstart(10)*(1+randn/10)];   
  370.        otherwise         
  371.      end % switch NumPeaks  
  372. end % for  
  373. % Multiplies each row by the corresponding amplitude and adds them up  
  374. model=PEAKHEIGHTS'*A;  
  375.   
  376. % Compare trial model to data segment and compute the fit error  
  377.   MeanFitError=100*norm(yy-model)./(sqrt(n)*max(yy));  
  378.   % Take only the single fit that has the lowest MeanFitError  
  379.   if MeanFitError<LowestError,   
  380.       if min(PEAKHEIGHTS)>0,  % Consider only fits with positive peak heights  
  381.         LowestError=MeanFitError;  % Assign LowestError to the lowest MeanFitError  
  382.         FitParameters=TrialParameters;  % Assign FitParameters to the fit with the lowest MeanFitError  
  383.         BestStart=newstart; % Assign BestStart to the start with the lowest MeanFitError  
  384.         height=PEAKHEIGHTS; % Assign height to the PEAKHEIGHTS with the lowest MeanFitError  
  385.         bestmodel=model; % Assign bestmodel to the model with the lowest MeanFitError  
  386.       end % if min(PEAKHEIGHTS)>0  
  387.   end % if MeanFitError<LowestError  
  388. end % for k (NumTrials)  
  389. %  
  390. % Construct model from best-fit parameters  
  391. AA=zeros(NumPeaks,100);  
  392. xxx=linspace(min(xx),max(xx));  
  393. for m=1:NumPeaks,  
  394.    switch peakshape  
  395.     case 1  
  396.         AA(m,:)=gaussian(xxx,FitParameters(2*m-1),FitParameters(2*m));  
  397.     case 2  
  398.         AA(m,:)=lorentzian(xxx,FitParameters(2*m-1),FitParameters(2*m));  
  399.     case 3  
  400.         AA(m,:)=logistic(xxx,FitParameters(2*m-1),FitParameters(2*m));  
  401.     case 4  
  402.         AA(m,:)=pearson(xxx,FitParameters(2*m-1),FitParameters(2*m),extra);  
  403.     case 5  
  404.         AA(m,:)=expgaussian(xxx,FitParameters(2*m-1),FitParameters(2*m),-extra*length(xxx)./length(xx))';  
  405.     case 6  
  406.         AA(m,:)=gaussian(xxx,FitParameters(m),FitParameters(NumPeaks+1));  
  407.     case 7  
  408.         AA(m,:)=lorentzian(xxx,FitParameters(m),FitParameters(NumPeaks+1));  
  409.     case 8  
  410.         AA(m,:)=expgaussian(xxx,FitParameters(m),FitParameters(NumPeaks+1),-extra*length(xxx)./length(xx))';  
  411.     case 9  
  412.         AA(m,:)=exppulse(xxx,FitParameters(2*m-1),FitParameters(2*m));    
  413.     case 10  
  414.         AA(m,:)=sigmoid(xxx,FitParameters(2*m-1),FitParameters(2*m));     
  415.        otherwise  
  416.   end % switch  
  417. end % for  
  418.   
  419. % Multiplies each row by the corresponding amplitude and adds them up  
  420. heightsize=size(height');  
  421. AAsize=size(AA);  
  422. if heightsize(2)==AAsize(1),  
  423.    mmodel=height'*AA;  
  424. else  
  425.     mmodel=height*AA;  
  426. end  
  427. % Top half of the figure shows original signal and the fitted model.  
  428. subplot(2,1,1);plot(xx+xoffset,yy,'b.'); % Plot the original signal in blue dots  
  429. hold on  
  430. for m=1:NumPeaks,  
  431.     plot(xxx+xoffset,height(m)*AA(m,:),'g')  % Plot the individual component peaks in green lines  
  432.     area(m)=trapz(xxx+xoffset,height(m)*AA(m,:)); % Compute the area of each component peak using trapezoidal method  
  433.     yi(m,:)=height(m)*AA(m,:); % (NEW) Place y values of individual model peaks into matrix yi  
  434. end  
  435. xi=xxx+xoffset; % (NEW) Place the x-values of the individual model peaks into xi  
  436.   
  437. % Mark starting peak positions with vertical dashed lines  
  438. for marker=1:NumPeaks,  
  439.     markx=BestStart((2*marker)-1);  
  440.     subplot(2,1,1);plot([markx+xoffset markx+xoffset],[0 max(yy)],'m--')  
  441. end % for  
  442. plot(xxx+xoffset,mmodel,'r');  % Plot the total model (sum of component peaks) in red lines  
  443. hold off;  
  444. axis([min(xx)+xoffset max(xx)+xoffset min(yy) max(yy)]);  
  445. switch AUTOZERO,  
  446.     case 0  
  447.     title('Peakfit 2.2. Autozero OFF.')  
  448.     case 1  
  449.     title('Peakfit 2.2. Linear autozero.')  
  450.     case 2  
  451.     title('Peakfit 2.2. Quadratic autozero.')  
  452. end  
  453. if peakshape==4||peakshape==5||peakshape==8, % Shapes with Extra factor  
  454.     xlabel(['Peaks = ' num2str(NumPeaks) '     Shape = ' ShapeString '     Error = ' num2str(round(100*LowestError)/100) '%    Extra = ' num2str(extra) ] )  
  455. else  
  456.     xlabel(['Peaks = ' num2str(NumPeaks) '     Shape = ' ShapeString '     Error = ' num2str(round(100*LowestError)/100) '%' ] )  
  457. end  
  458.   
  459. % Bottom half of the figure shows the residuals and displays RMS error  
  460. % between original signal and model  
  461. residual=yy-bestmodel;  
  462. subplot(2,1,2);plot(xx+xoffset,residual,'b.')  
  463. axis([min(xx)+xoffset max(xx)+xoffset min(residual) max(residual)]);  
  464. xlabel('Residual Plot')  
  465.   
  466. % Put results into a matrix, one row for each peak, showing peak index number,  
  467. % position, amplitude, and width.  
  468. for m=1:NumPeaks,  
  469.     if m==1,  
  470.         if peakshape==6||peakshape==7||peakshape==8, % equal-width peak models  
  471.            FitResults=[[round(m) FitParameters(m)+xoffset height(m) abs(FitParameters(NumPeaks+1)) area(m)]];  
  472.         else  
  473.            FitResults=[[round(m) FitParameters(2*m-1)+xoffset height(m) abs(FitParameters(2*m)) area(m)]];  
  474.         end % if peakshape  
  475.     else  
  476.         if peakshape==6||peakshape==7||peakshape==8, % equal-width peak models  
  477.            FitResults=[FitResults ; [round(m) FitParameters(m)+xoffset height(m) abs(FitParameters(NumPeaks+1)) area(m)]];  
  478.         else  
  479.            FitResults=[FitResults ; [round(m) FitParameters(2*m-1)+xoffset height(m) abs(FitParameters(2*m)) area(m)]];  
  480.         end % if peakshape  
  481.      end % m==1  
  482. end % for m=1:NumPeaks  
  483.   
  484. % Display Fit Results on upper graph  
  485. subplot(2,1,1);  
  486. startx=min(xx)+xoffset+(max(xx)-min(xx))./20;  
  487. dxx=(max(xx)-min(xx))./10;  
  488. dyy=(max(yy)-min(yy))./10;  
  489. starty=max(yy)-dyy;  
  490. FigureSize=get(gcf,'Position');  
  491. if peakshape==9||peakshape==10,  
  492.     text(startx,starty+dyy/2,['Peak #          tau1           Height           tau2             Area'] );  
  493. else  
  494.     text(startx,starty+dyy/2,['Peak #          Position        Height         Width             Area'] );   
  495. end  
  496. % Display FitResults using sprintf  
  497.  for peaknumber=1:NumPeaks,  
  498.     for column=1:5,  
  499.         itemstring=sprintf('%0.4g',FitResults(peaknumber,column));  
  500.         xposition=startx+(1.7.*dxx.*(column-1).*(600./FigureSize(3)));  
  501.         yposition=starty-peaknumber.*dyy.*(400./FigureSize(4));  
  502.         text(xposition,yposition,itemstring);  
  503.     end  
  504.  end  
  505. % ----------------------------------------------------------------------  
  506. function start=calcstart(xx,NumPeaks,xoffset)  
  507.   n=max(xx)-min(xx);  
  508.   start=[];  
  509.   startpos=[n/(NumPeaks+1):n/(NumPeaks+1):n-(n/(NumPeaks+1))]+min(xx);  
  510.   for marker=1:NumPeaks,  
  511.       markx=startpos(marker)+ xoffset;  
  512.       start=[start markx n/5];  
  513.   end % for marker  
  514. % ----------------------------------------------------------------------  
  515. function [index,closestval]=val2ind(x,val)  
  516. % Returns the index and the value of the element of vector x that is closest to val  
  517. % If more than one element is equally close, returns vectors of indicies and values  
  518. % Tom O'Haver (toh@umd.edu) October 2006  
  519. % Examples: If x=[1 2 4 3 5 9 6 4 5 3 1], then val2ind(x,6)=7 and val2ind(x,5.1)=[5 9]  
  520. % [indices values]=val2ind(x,3.3) returns indices = [4 10] and values = [3 3]  
  521. dif=abs(x-val);  
  522. index=find((dif-min(dif))==0);  
  523. closestval=x(index);  
  524. % ----------------------------------------------------------------------  
  525. function err = fitgaussian(lambda,t,y)  
  526. % Fitting function for a Gaussian band signal.  
  527. global PEAKHEIGHTS  
  528. numpeaks=round(length(lambda)/2);  
  529. A = zeros(length(t),numpeaks);  
  530. for j = 1:numpeaks,  
  531.     A(:,j) = gaussian(t,lambda(2*j-1),lambda(2*j))';  
  532. end   
  533. PEAKHEIGHTS = abs(A\y');  
  534. z = A*PEAKHEIGHTS;  
  535. err = norm(z-y');  
  536. % ----------------------------------------------------------------------  
  537. function err = fitewgaussian(lambda,t,y)  
  538. % Fitting function for a Gaussian band signal with equal peak widths.  
  539. global PEAKHEIGHTS  
  540. numpeaks=round(length(lambda)-1);  
  541. A = zeros(length(t),numpeaks);  
  542. for j = 1:numpeaks,  
  543.     A(:,j) = gaussian(t,lambda(j),lambda(numpeaks+1))';  
  544. end  
  545. PEAKHEIGHTS = abs(A\y');  
  546. z = A*PEAKHEIGHTS;  
  547. err = norm(z-y');  
  548. % ----------------------------------------------------------------------  
  549. function err = fitgaussianfw(lambda,t,y)  
  550. % Fitting function for a Gaussian band signal with fixed peak widths.  
  551. global PEAKHEIGHTS  
  552. numpeaks=round(length(lambda)-1);  
  553. A = zeros(length(t),numpeaks);  
  554. for j = 1:numpeaks,  
  555.     A(:,j) = gaussian(t,lambda(j),lambda(numpeaks+1))';  
  556. end  
  557. PEAKHEIGHTS = abs(A\y');  
  558. z = A*PEAKHEIGHTS;  
  559. err = norm(z-y');  
  560. % ----------------------------------------------------------------------  
  561. function err = fitlorentziancw(lambda,t,y)  
  562. % Fitting function for a Lorentzian band signal with equal peak widths.  
  563. global PEAKHEIGHTS  
  564. numpeaks=round(length(lambda)-1);  
  565. A = zeros(length(t),numpeaks);  
  566. for j = 1:numpeaks,  
  567.     A(:,j) = lorentzian(t,lambda(j),lambda(numpeaks+1))';  
  568. end  
  569. PEAKHEIGHTS = abs(A\y');  
  570. z = A*PEAKHEIGHTS;  
  571. err = norm(z-y');  
  572. % ----------------------------------------------------------------------  
  573. function g = gaussian(x,pos,wid)  
  574. %  gaussian(X,pos,wid) = gaussian peak centered on pos, half-width=wid  
  575. %  X may be scalar, vector, or matrix, pos and wid both scalar  
  576. % Examples: gaussian([0 1 2],1,2) gives result [0.5000    1.0000    0.5000]  
  577. % plot(gaussian([1:100],50,20)) displays gaussian band centered at 50 with width 20.  
  578. g = exp(-((x-pos)./(0.6005615.*wid)) .^2);  
  579. % ----------------------------------------------------------------------  
  580. function err = fitlorentzian(lambda,t,y)  
  581. %   Fitting function for single lorentzian, lambda(1)=position, lambda(2)=width  
  582. %   Fitgauss assumes a lorentzian function   
  583. global PEAKHEIGHTS  
  584. A = zeros(length(t),round(length(lambda)/2));  
  585. for j = 1:length(lambda)/2,  
  586.     A(:,j) = lorentzian(t,lambda(2*j-1),lambda(2*j))';  
  587. end  
  588. PEAKHEIGHTS = A\y';  
  589. z = A*PEAKHEIGHTS;  
  590. err = norm(z-y');  
  591. % ----------------------------------------------------------------------  
  592. function g = lorentzian(x,position,width)  
  593. % lorentzian(x,position,width) Lorentzian function.  
  594. % where x may be scalar, vector, or matrix  
  595. % position and width scalar  
  596. % T. C. O'Haver, 1988  
  597. % Example: lorentzian([1 2 3],2,2) gives result [0.5 1 0.5]  
  598. g=ones(size(x))./(1+((x-position)./(0.5.*width)).^2);  
  599. % ----------------------------------------------------------------------  
  600. function err = fitlogistic(lambda,t,y)  
  601. %   Fitting function for logistic, lambda(1)=position, lambda(2)=width  
  602. %   between the data and the values computed by the current  
  603. %   function of lambda.  Fitlogistic assumes a logistic function   
  604. %  T. C. O'Haver, May 2006  
  605. global PEAKHEIGHTS  
  606. A = zeros(length(t),round(length(lambda)/2));  
  607. for j = 1:length(lambda)/2,  
  608.     A(:,j) = logistic(t,lambda(2*j-1),lambda(2*j))';  
  609. end  
  610. PEAKHEIGHTS = A\y';  
  611. z = A*PEAKHEIGHTS;  
  612. err = norm(z-y');  
  613. % ----------------------------------------------------------------------  
  614. function g = logistic(x,pos,wid)  
  615. % logistic function.  pos=position; wid=half-width (both scalar)  
  616. % logistic(x,pos,wid), where x may be scalar, vector, or matrix  
  617. % pos=position; wid=half-width (both scalar)  
  618. % T. C. O'Haver, 1991   
  619. n = exp(-((x-pos)/(.477.*wid)) .^2);  
  620. g = (2.*n)./(1+n);  
  621. % ----------------------------------------------------------------------  
  622. function err = fitlognormal(lambda,t,y)  
  623. %   Fitting function for lognormal, lambda(1)=position, lambda(2)=width  
  624. %   between the data and the values computed by the current  
  625. %   function of lambda.  Fitlognormal assumes a lognormal function   
  626. %  T. C. O'Haver, May 2006  
  627. global PEAKHEIGHTS  
  628. A = zeros(length(t),round(length(lambda)/2));  
  629. for j = 1:length(lambda)/2,  
  630.     A(:,j) = lognormal(t,lambda(2*j-1),lambda(2*j))';  
  631. end  
  632. PEAKHEIGHTS = A\y';  
  633. z = A*PEAKHEIGHTS;  
  634. err = norm(z-y');  
  635. % ----------------------------------------------------------------------  
  636. function g = lognormal(x,pos,wid)  
  637. % lognormal function.  pos=position; wid=half-width (both scalar)  
  638. % lognormal(x,pos,wid), where x may be scalar, vector, or matrix  
  639. % pos=position; wid=half-width (both scalar)  
  640. % T. C. O'Haver, 1991    
  641. g = exp(-(log(x/pos)/(0.01.*wid)) .^2);  
  642. % ----------------------------------------------------------------------  
  643. function err = fitpearson(lambda,t,y,shapeconstant)  
  644. %   Fitting functions for a Pearson 7 band signal.  
  645. % T. C. O'Haver (toh@umd.edu),   Version 1.3, October 23, 2006.  
  646. global PEAKHEIGHTS  
  647. A = zeros(length(t),round(length(lambda)/2));  
  648. for j = 1:length(lambda)/2,  
  649.     A(:,j) = pearson(t,lambda(2*j-1),lambda(2*j),shapeconstant)';  
  650. end  
  651. PEAKHEIGHTS = A\y';  
  652. z = A*PEAKHEIGHTS;  
  653. err = norm(z-y');  
  654. % ----------------------------------------------------------------------  
  655. function g = pearson(x,pos,wid,m)  
  656. % Pearson VII function.   
  657. % g = pearson7(x,pos,wid,m) where x may be scalar, vector, or matrix  
  658. % pos=position; wid=half-width (both scalar)  
  659. % m=some number  
  660. %  T. C. O'Haver, 1990    
  661. g=ones(size(x))./(1+((x-pos)./((0.5.^(2/m)).*wid)).^2).^m;  
  662. % ----------------------------------------------------------------------  
  663. function err = fitexpgaussian(lambda,t,y,timeconstant)  
  664. %   Fitting functions for a exponentially-broadened Gaussian band signal.  
  665. %  T. C. O'Haver, October 23, 2006.  
  666. global PEAKHEIGHTS  
  667. A = zeros(length(t),round(length(lambda)/2));  
  668. for j = 1:length(lambda)/2,  
  669.     A(:,j) = expgaussian(t,lambda(2*j-1),lambda(2*j),timeconstant);  
  670. end  
  671. PEAKHEIGHTS = A\y';  
  672. z = A*PEAKHEIGHTS;  
  673. err = norm(z-y');  
  674. % ----------------------------------------------------------------------  
  675. function err = fitexpewgaussian(lambda,t,y,timeconstant)  
  676. % Fitting function for exponentially-broadened Gaussian bands with equal peak widths.  
  677. global PEAKHEIGHTS  
  678. numpeaks=round(length(lambda)-1);  
  679. A = zeros(length(t),numpeaks);  
  680. for j = 1:numpeaks,  
  681.     A(:,j) = expgaussian(t,lambda(j),lambda(numpeaks+1),timeconstant);  
  682. end  
  683. PEAKHEIGHTS = abs(A\y');  
  684. z = A*PEAKHEIGHTS;  
  685. err = norm(z-y');  
  686. % ----------------------------------------------------------------------  
  687. function g = expgaussian(x,pos,wid,timeconstant)  
  688. %  Exponentially-broadened gaussian(x,pos,wid) = gaussian peak centered on pos, half-width=wid  
  689. %  x may be scalar, vector, or matrix, pos and wid both scalar  
  690. %  T. C. O'Haver, 2006  
  691. g = exp(-((x-pos)./(0.6005615.*wid)) .^2);  
  692. g = ExpBroaden(g',timeconstant);  
  693. % ----------------------------------------------------------------------  
  694. function yb = ExpBroaden(y,t)  
  695. % ExpBroaden(y,t) convolutes y by an exponential decay of time constant t  
  696. % by multiplying Fourier transforms and inverse transforming the result.  
  697. fy=fft(y);  
  698. a=exp(-[1:length(y)]./t);  
  699. fa=fft(a);  
  700. fy1=fy.*fa';             
  701. yb=real(ifft(fy1))./sum(a);    
  702. % ----------------------------------------------------------------------  
  703. function err = fitexppulse(tau,x,y)  
  704. % Iterative fit of the sum of exponental pulses  
  705. % of the form Height.*exp(-tau1.*x).*(1-exp(-tau2.*x)))  
  706. global PEAKHEIGHTS  
  707. A = zeros(length(x),round(length(tau)/2));  
  708. for j = 1:length(tau)/2,  
  709.     A(:,j) = exppulse(x,tau(2*j-1),tau(2*j));  
  710. end  
  711. PEAKHEIGHTS =abs(A\y');  
  712. z = A*PEAKHEIGHTS;  
  713. err = norm(z-y');  
  714. % ----------------------------------------------------------------------  
  715. function g = exppulse(x,t1,t2)  
  716. % Exponential pulse of the form   
  717. % Height.*exp(-tau1.*x).*(1-exp(-tau2.*x)))  
  718. e=(x-t1)./t2;  
  719. p = 4*exp(-e).*(1-exp(-e));  
  720. p=p .* [p>0];  
  721. g = p';  
  722. % ----------------------------------------------------------------------  
  723. function err = fitsigmoid(tau,x,y)  
  724. % Fitting function for iterative fit to the sum of  
  725. % sigmiods of the form Height./(1 + exp((t1 - t)/t2))  
  726. global PEAKHEIGHTS  
  727. A = zeros(length(x),round(length(tau)/2));  
  728. for j = 1:length(tau)/2,  
  729.     A(:,j) = sigmoid(x,tau(2*j-1),tau(2*j));  
  730. end  
  731. PEAKHEIGHTS = A\y';  
  732. z = A*PEAKHEIGHTS;  
  733. err = norm(z-y');  
  734. % ----------------------------------------------------------------------  
  735. function g=sigmoid(x,t1,t2)  
  736. g=1./(1 + exp((t1 - x)./t2))';  
  • 5
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
% This folder contains a collection of "fitting" functions. % (Some has demo options - the third section) % The GENERAL input to the functions should be samples of the distribution. % % for example, if we are to fit a normal distribution ('gaussian') with a mean "u" and varaince "sig"^2 % then the samples will distribute like: % samples = randn(1,10000)*sig + u % %fitting with Least-Squares is done on the histogram of the samples. % fitting with Maximum likelihood is done directly on the samples. % % % Contents of this folder % ======================= % 1) Maximum likelihood estimators % 2) Least squares estimators % 3) EM algorithm for estimation of multivariant gaussian distribution (mixed gaussians) % 4) added folders: Create - which create samples for the EM algorithm test % Plot - used to plot each of the distributions (parametric plot) % % % % % % Maximum likelihood estimators % ============================= % fit_ML_maxwell - fit maxwellian distribution % fit_ML_rayleigh - fit rayleigh distribution % (which is for example: sqrt(abs(randn)^2+abs(randn)^2)) % fit_ML_laplace - fit laplace distribution % fit_ML_log_normal- fit log-normal distribution % fit_ML_normal - fit normal (gaussian) distribution % % NOTE: all estimators are efficient estimators. for this reason, the distribution % might be written in a different way, for example, the "Rayleigh" distribution % is given with a parameter "s" and not "s^2". % % % least squares estimators % ========================= % fit_maxwell_pdf - fits a given curve of a maxwellian distribution % fit_rayleigh_pdf - fits a given curve of a rayleigh distribution % % NOTE: these fit function are used on a histogram output which is like a sampled % distribution function. the given curve MUST be normalized, since the estimator % is trying to fit a normalized distribution function. % % % % % Multivariant Gaussian distribution % ================================== % for demo of 1

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值