fit gaussian with lsqcurvefit in matlab

To fit a Gaussian function using lsqcurvefit in MATLAB, you need to follow these steps:

  1. Define the Gaussian function that you want to fit. It can be written as:
main.m
function y = gaussian(x, params)
    mu = params(1);
    sigma = params(2);
    A = params(3);
    
    y = A * exp(-(x - mu).^2 / (2 * sigma^2));
end
151 chars
8 lines
  1. Generate some sample data to fit the Gaussian function to. For example:
main.m
x = linspace(-10, 10, 100);
params_true = [0, 1, 1];  % True parameters: mean, standard deviation, amplitude
y_true = gaussian(x, params_true);
noise = 0.1 * randn(size(x));
y = y_true + noise;
194 chars
6 lines
  1. Define the objective function for lsqcurvefit to minimize. This function computes the residuals between the observed data and the model prediction:
main.m
function residuals = gaussian_fit(params, x, y)
    predicted_y = gaussian(x, params);
    residuals = y - predicted_y;
end
124 chars
5 lines
  1. Use lsqcurvefit to optimize the parameters of the Gaussian function:
main.m
params0 = [0, 1, 1];  % Initial guess for parameters
params_fit = lsqcurvefit(@gaussian, params0, x, y);
105 chars
3 lines
  1. Plot the original data, the true Gaussian function, and the fitted Gaussian function:
main.m
y_fit = gaussian(x, params_fit);

plot(x, y, 'o', 'DisplayName', 'Data');
hold on;
plot(x, y_true, 'r', 'DisplayName', 'True Gaussian');
plot(x, y_fit, 'g', 'DisplayName', 'Fitted Gaussian');
xlabel('x');
ylabel('y');
legend();
228 chars
10 lines

This code will fit a Gaussian function to the given data using lsqcurvefit in MATLAB. You can adjust the parameters and data as necessary for your specific application.

Note that lsqcurvefit returns the fitted parameter values that minimize the sum of squares of the residuals.

related categories

gistlibby LogSnag