gaussian fit in matlab

To perform a Gaussian fit in Matlab, we need to use the fit() function. First, we need to define our Gaussian function as a string. We will use the formula for the Gaussian distribution:

main.m
y(x) = a * exp(-(x-b)^2/(2*c^2)) + d
37 chars
2 lines

where a is the amplitude, b is the mean, c is the standard deviation, and d is the offset.

Next, we need to create a fittype object using the fittype() function. We will specify the independent variable x, and the dependent variable y. We will use the 'NonlinearLeastSquares' method for optimization.

main.m
gaussFunction = 'a * exp(-(x-b)^2/(2*c^2)) + d';
f = fittype(gaussFunction, 'independent', 'x', 'dependent', 'y', 'problem', {'a','b','c','d'}, 'method', 'NonlinearLeastSquares');
180 chars
3 lines

We can now use the fit() function to perform the curve fitting. We need to specify the x and y data, as well as the initial guess for the parameters. We can do this using the startPoint argument.

main.m
xdata = [1 2 3 4 5]; % example x data
ydata = [0.2 0.7 1.6 2.5 3.9]; % example y data

% set initial guess for parameters
a0 = max(ydata); % amplitude
b0 = mean(xdata); % mean
c0 = std(xdata); % standard deviation
d0 = min(ydata); % offset

% perform curve fitting
fitResult = fit(xdata', ydata', f, 'StartPoint', [a0 b0 c0 d0]);
330 chars
12 lines

We can now plot the results using the plot() function. We will plot the original data points as well as the curve fit.

main.m
% plot the original data points and the fitted curve
plot(xdata, ydata, 'ro', 'DisplayName', 'data')
hold on
plot(fitResult, 'DisplayName', 'fit')
hold off
legend
163 chars
7 lines

This should give us a Gaussian fit to our data.

gistlibby LogSnag