Curve Fitting in MATLAB: A Step-by-Step Guide


MATLAB's curve fitting toolbox allows you to fit mathematical models to experimental or observational data. In this guide, we'll take you through the process of curve fitting using MATLAB, step by step, with sample code and examples.

Load Data

To start curve fitting, you need to load your data into MATLAB. You can use the load function or manually enter your data. Let's load an example dataset:

% Example: Load data
data = load('example_data.mat');
x = data.x;
y = data.y;

Select a Fitting Model

The next step is to choose a mathematical model that describes your data. You can select from various predefined models or define your own custom model. For this example, we'll use a simple linear model.

% Example: Select a linear model
fitting_model = @(a, x) a(1) * x + a(2);

Perform the Fit

MATLAB provides a function called fit to perform the curve fitting. Here's how to fit the data to the selected model:

% Example: Perform the fit
fit_result = fit(x, y, fitting_model, 'StartPoint', [1, 0]);

Visualize the Fit

It's essential to visualize the fit to assess how well the model describes the data. You can use the plot function to visualize the data and the fitted curve.

% Example: Visualize the fit
plot(x, y, 'o', 'DisplayName', 'Data');
hold on;
plot(fit_result, 'r', 'DisplayName', 'Fitted Curve');
grid on;

Evaluate the Fit

You can evaluate the quality of the fit by checking the goodness of fit statistics and the coefficients of determination (R-squared value).

% Example: Evaluate the fit
sse = sum((y - fit_result(x)).^2);
sst = sum((y - mean(y)).^2);
rsquared = 1 - sse / sst;
disp(['R-squared value: ', num2str(rsquared)]);


This guide has taken you through the process of curve fitting in MATLAB. Curve fitting is a valuable tool for understanding and modeling data. As you gain experience, you can explore more complex models and advanced curve fitting techniques to address various real-world problems.

Enjoy fitting curves to your data with MATLAB!