%%%%%%%% To fit a 2D gaussian to the raster maps Use starting best guess values of Expects input arrays from e.g. meshgrid XI, YI and ZI Code then makes into suitable vectors amp = amplitude sigmax = x-width sigmay = y-width x0 = offset in x y0 = offset in y0 If no start points given, it will estimate from the data ACT 11/5/2012 %%%%%%%%%%%%%
0001 function [sf gof t] = gauss2D_fit_act(XI,YI,ZI,a1,sigmax, sigmay,x0,y0) 0002 0003 0004 %%%%%%%%% 0005 % To fit a 2D gaussian to the raster maps 0006 % Use starting best guess values of 0007 % 0008 % Expects input arrays from e.g. meshgrid XI, YI and ZI 0009 % Code then makes into suitable vectors 0010 % amp = amplitude 0011 % sigmax = x-width 0012 % sigmay = y-width 0013 % x0 = offset in x 0014 % y0 = offset in y0 0015 % 0016 % If no start points given, it will estimate from the data 0017 % 0018 % ACT 11/5/2012 0019 % 0020 %%%%%%%%%%%%%% 0021 0022 % Creat suitable vectors 0023 X = XI(:); 0024 Y = YI(:); 0025 Z = ZI(:); 0026 0027 % Define the gaussian 0028 0029 gauss2 = fittype( 'a1*exp(-(x-x0).^2/(2*sigmax^2)-(y-y0).^2/(2*sigmay^2))','independent', {'x', 'y'},'dependent', 'z' ); 0030 0031 % Make sure we have a starting point 0032 0033 if(nargin<8) 0034 0035 a1 = max(Z(:)); % height, determine from image. may want to subtract background 0036 sigmax = 0.4; % guess width 0037 sigmay = 0.4; % guess width 0038 x0 = mean(X); % guess position (center seems a good place to start) 0039 y0 = mean(Y); 0040 end 0041 0042 % Set some fit options 0043 options = fitoptions('Method','NonlinearLeastSquares'); 0044 options.StartPoint = [a1,sigmax,sigmay,x0,y0]; 0045 0046 %Check for Nans in the data 0047 aa = isnan(Z); 0048 options.Exclude = aa; 0049 0050 % Compute fit and plot figure 0051 0052 [sf gof t] = fit([X,Y],double(Z),gauss2,options); 0053 0054 0055 figure(20); clf; plot(sf,[X,Y],Z); 0056 0057 %sf.x0 and sf.y0 is the center of gaussian. 0058 %sf.sigmax etc will get you the other parameters.