2d gaussian surface fitting in matlab

To perform a 2D Gaussian surface fitting in MATLAB, you can use the lsqcurvefit function along with a custom Gaussian function. Here's an example of how you can do it:

main.m
% Generate some example data
[x, y] = meshgrid(1:100, 1:100);
A = 10; % amplitude
x0 = 50; % x-coordinate of the center
y0 = 50; % y-coordinate of the center
sigma_x = 20; % standard deviation in the x-direction
sigma_y = 10; % standard deviation in the y-direction
z = A * exp(-(x - x0).^2 / (2 * sigma_x^2) - (y - y0).^2 / (2 * sigma_y^2));

% Add some noise to the data
rng(0); % for reproducibility
z_noisy = z + randn(size(z));

% Define the Gaussian function for fitting
gaussian = @(x, p) p(1) * exp(-(x(:, 1) - p(2)).^2 / (2 * p(3)^2) - (x(:, 2) - p(4)).^2 / (2 * p(5)^2));

% Initial parameter guess
p0 = [max(z_noisy(:)), x0, sigma_x, y0, sigma_y];

% Perform the fitting
p_fit = lsqcurvefit(gaussian, p0, [x(:), y(:)], z_noisy(:));

% Extract the fitted parameters
A_fit = p_fit(1);
x0_fit = p_fit(2);
sigma_x_fit = p_fit(3);
y0_fit = p_fit(4);
sigma_y_fit = p_fit(5);

% Generate the fitted surface
z_fit = gaussian([x(:), y(:)], p_fit);
z_fit = reshape(z_fit, size(x));

% Plotting the results
figure;
subplot(1, 2, 1);
surf(x, y, z_noisy);
title('Noisy Data');
subplot(1, 2, 2);
surf(x, y, z_fit);
title('Fitted Surface');
1137 chars
42 lines

In this example, we start by generating some example data with a 2D Gaussian shape. Then, we add some random noise to the data. We define a custom Gaussian function that takes the coordinate values and the fitting parameters as inputs and returns the Gaussian values. We also define an initial guess for the parameters.

Next, we use the lsqcurvefit function to fit the Gaussian function to the noisy data. The function minimizes the sum of squares between the observed values and the predicted values using the Levenberg-Marquardt algorithm. The fitted parameters are then extracted.

Finally, the fitted surface is generated using the fitted parameters, and we plot both the noisy data and the fitted surface for comparison.

Note that the example assumes a 2D Gaussian surface with independent standard deviations in the x and y directions. You can modify the Gaussian function and the fitting parameters according to your specific needs.

gistlibby LogSnag