fit multiple gaussian surface peaks in matlab

To fit multiple Gaussian peaks in a surface data using MATLAB, you can use the "lsqcurvefit" function combined with the "gaussianPeak" function. Here is an example code to illustrate the process:

main.m
% Define the surface data (replace with your own data)
x = 1:100;
y = 1:100;
[X, Y] = meshgrid(x, y);
Z = 2*exp(-((X-30).^2 + (Y-70).^2)/50^2) + ...
    1.5*exp(-((X-70).^2 + (Y-40).^2)/30^2) + ...
    3*exp(-((X-50).^2 + (Y-80).^2)/40^2) + ...
    randn(size(X))*0.2;

% Define the number of Gaussian peaks you want to fit
nPeaks = 3;

% Define initial guesses for peak parameters
initialParams = [];
for i = 1:nPeaks
    initialParams = [initialParams, [max(Z(:)), mean(x), std(x), max(Z(:))/10]];
end

% Define the function to fit (sum of Gaussian peaks)
gaussianPeak = @(params, xy) sum(params(1:nPeaks) .* ...
    exp(-(xy(:,1) - params(nPeaks+1:2*nPeaks)).^2 ./ ...
    (2*params(2*nPeaks+1:3*nPeaks).^2)));

% Perform the fitting using lsqcurvefit
fitParams = lsqcurvefit(gaussianPeak, initialParams, [X(:), Y(:)], Z(:));

% Evaluate the fitted function
fittedZ = reshape(gaussianPeak(fitParams, [X(:), Y(:)]), size(X));

% Plot the original and fitted surface data
figure;
subplot(1, 2, 1);
surf(X, Y, Z);
title('Original Data');
subplot(1, 2, 2);
surf(X, Y, fittedZ);
title('Fitted Data');
1099 chars
38 lines

In this example, I created a synthetic surface data with three Gaussian peaks and added some random noise. You can replace Z with your own surface data. The code then fits the surface data using the lsqcurvefit function, which minimizes the sum of squared differences between the fitted function and the data. The fitted Gaussian peaks are then evaluated using the fitted parameters.

Note that the initial guesses for the peak parameters are essential for successful fitting. If you have an estimate of the parameters, you can modify the initialParams array to reflect that.

Make sure you have the Curve Fitting Toolbox installed to use the lsqcurvefit function.

gistlibby LogSnag