fit a gaussian to data in matlab

Here's an example code to fit a Gaussian curve to data in Matlab using the fit function:

main.m
% Generate example data
x = linspace(-5, 5, 100);
y = 10*exp(-(x+1).^2/2) + randn(size(x));

% Define Gaussian model function
gaussian = @(a, x) a(1)*exp(-(x-a(2)).^2/(2*a(3)^2));

% Fit Gaussian to data
fitted_model = fit(x', y', gaussian, 'StartPoint', [max(y), mean(x), std(x)]);

% Plot data and fitted curve
plot(x, y, 'o')
hold on
plot(x, fitted_model(x), 'r-', 'LineWidth', 2)
xlabel('X')
ylabel('Y')
legend('Data', 'Fitted Gaussian')
442 chars
18 lines

In this example, we first generate example data x and y. Then we define a Gaussian model function using an anonymous function gaussian, which takes in a vector of parameters a and a vector of inputs x. We then use the fit function to fit the Gaussian model to the data (x and y) using the starting guess [max(y), mean(x), std(x)] for the parameters a. Finally, we plot the data and the fitted curve using the plot function.

gistlibby LogSnag