nonlinear fit using a function in matlab

main.m
% Define the function you want to fit
fun = @(x, params) params(1) * exp(-params(2) * x) + params(3);

% Generate some example data
x = 0:0.1:10;
params_true = [2, 0.5, 1];
y_true = fun(x, params_true);
y_noisy = y_true + 0.1*randn(size(x));

% Define initial guess for the parameters
params_guess = [1, 1, 0];

% Perform nonlinear curve fitting
params_fit = lsqcurvefit(fun, params_guess, x, y_noisy);

% Extract the fitted parameters
a_fit = params_fit(1);
b_fit = params_fit(2);
c_fit = params_fit(3);

% Generate the fitted curve
y_fit = fun(x, params_fit);

% Plot the results
figure;
plot(x, y_noisy, 'ro', x, y_true, 'k-', x, y_fit, 'b--');
legend('Noisy Data', 'True Curve', 'Fitted Curve');
xlabel('x');
ylabel('y');
title('Nonlinear Curve Fitting');
760 chars
31 lines

This code snippet demonstrates how to perform nonlinear curve fitting in MATLAB using lsqcurvefit with a user-defined function.

related categories

gistlibby LogSnag