Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Curve Fitting Algorithms and MATLAB Implementation

Tech 1

Curve Fitting vs. Interpolation

Curve fitting constructs a single continuous curve that minimizes the overall distance to a set of data points, rather than passing through every single point. In contrast, interpolation strictly forces the curve through all observed samples, often requiring piecewise approaches to mitigate Runge's phenomenon. Fitting is generally preferred when the objective is to extract an underlying deterministic mathematical relationship from noisy observations.

Least Squares Optimization

The standard approach for determining the optimal fitted curve is the least squares method. This technique minimizes the sum of the squared differences between the observed values and the values predicted by the model.

Evaluating Fit Quality: R-squared and SSE

The Sum of Squared Errors (SSE) serves as a fundamental metric for goodness of fit. For models that are linear with respect to their parameters, the coefficient of determination (R-squared) is the standard evaluation metric. For nonlinear or highly complex parameter models, SSE is typically sufficient. It is crucial to note that "linear" in this context refers to parameter linearity, not variable linearity. For instance, an exponential model can be transformed into a parameter-linear model by applying a logarithmic transformation.

MATLAB Implementation

Anonymous functions in MATLAB are defined using the @ symbol, capturing parameters within the expression: func_handle = @(arg1, arg2) expression. For visualizing single-variable anonymous functions, fplot(func_handle, x_range) is highly effective.

% Initialize data vectors
obs_x = [2.5, 3.5, 4.5, 5.5, 6.5];
obs_y = [4.2, 5.1, 5.8, 6.9, 8.1];
num_pts = length(obs_x);

% Plot observed data points
scatter(obs_x, obs_y, 'o');
xlabel('Independent Variable');
ylabel('Dependent Variable');
grid on;

% Calculate linear fit coefficients (slope and intercept)
sum_x = sum(obs_x);
sum_y = sum(obs_y);
sum_xy = sum(obs_x .* obs_y);
sum_x2 = sum(obs_x .* obs_x);

slope = (num_pts * sum_xy - sum_x * sum_y) / (num_pts * sum_x2 - sum_x * sum_x);
intercept = (sum_x2 * sum_y - sum_xy * sum_x) / (num_pts * sum_x2 - sum_x * sum_x);

% Define and plot the fitted curve using an anonymous function
linear_fit = @(val) slope * val + intercept;
fplot(linear_fit, [min(obs_x), max(obs_x)]);
legend('Observations', 'Linear Fit', 'Location', 'southeast');

% Compute goodness of fit metrics
predicted_y = linear_fit(obs_x);
mean_y = mean(obs_y);

ssr = sum((predicted_y - mean_y).^2);  % Regression Sum of Squares
sse = sum((predicted_y - obs_y).^2);    % Error Sum of Squares
sst = sum((obs_y - mean_y).^2);         % Total Sum of Squares

% Verify SST decomposition: SST = SSR + SSE
disp(sst - sse - ssr); % Expected output: 0

r_squared = ssr / sst;

Curve Fitting Toolbox

MATLAB provides an interactive Curve Fitter app accessible via the cftool command. When utilizing the "Custom Equation" option, ensure vectorized operations are employed (using .* and ./) since input data arrays are inherently vectors. If the fitting algorithm fails to converge ("Fit computation did not converge"), access the "Fit Options" dialog to manually adjust the initial parameter estimates (StartPoint). The app supports exporting both the generated plots and the equivalent MATLAB source code.

Generating Random Data

Simulating synthetic datasets requires various rendom number generators:

% Uniform discrete integers: randi(max_val, rows, cols)
mat_int = randi([-5, 5], 1, 10); % 1x10 matrix of integers from -5 to 5

% Uniform continuous between 0 and 1: rand(rows, cols)
mat_uniform = rand(1, 5); % 1x5 matrix in [0,1]
% Scaling to a custom range [lower_b, upper_b]:
lower_b = 2; upper_b = 5;
mat_scaled = lower_b + (upper_b - lower_b) * rand(1, 5);

% Normal distribution: normrnd(mu, sigma, rows, cols)
% mat_normal = normrnd(0, 2, 3, 4); % Mean 0, StdDev 2, 3x4 matrix

% Rounding to specified decimal/place: roundn(val, digits)
% 0: ones place, 1: tens, -1: tenths, -2: hundredths
pi_approx = roundn(3.1415, -2); % Result: 3.14

If the normrnd function triggers an "Unrecognized function or variable" error, execute doc normrnd in the command window to locate the required Statistics and Machine Learning Toolbox, and follow the installation prompts.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.