Sure! Below is a MATLAB script that implements Weighted Least Squares (WLS) for fitting a straight line (linear regression) of the form:
[
y = a x + b
]
given vectors x, y, and sigma, where:
x: independent variable (n×1)
y: dependent variable (n×1)
sigma: standard deviation (error) of each y measurement (n×1)
✅ Weighted Least Squares (WLS) MATLAB Script
% Weighted Least Squares Linear Fit
% Inputs: x, y, sigma (measurement standard deviations)
% Outputs: optimal slope (a), intercept (b), and their uncertainties
% ========== Example Inputs (can replace with your own data) ==========
x = [1; 2; 3; 4; 5];
y = [2.1; 3.9; 6.0; 7.8; 10.2];
sigma = [0.2; 0.2; 0.3; 0.2; 0.4]; % Known standard deviation for each y
% ======================================================================
% Ensure column vectors
x = x(:);
y = y(:);
sigma = sigma(:);
% Construct design matrix A and weight matrix W
A = [x, ones(size(x))]; % [x 1] for slope and intercept
W = diag(1 ./ sigma.^2); % Weight matrix: inverse variances
% Weighted Least Squares Solution: beta = inv(A'*W*A) * A'*W * y
Cov_beta = inv(A' * W * A); % Covariance matrix of estimates
beta = Cov_beta * (A' * W * y); % [a; b]
% Extract slope and intercept
a = beta(1);
b = beta(2);
% Uncertainties (standard deviations)
sigma_a = sqrt(Cov_beta(1,1));
sigma_b = sqrt(Cov_beta(2,2));
% Display results
fprintf('Weighted Linear Fit Results:\n');
fprintf('Slope (a) = %.4f ± %.4f\n', a, sigma_a);
fprintf('Intercept (b) = %.4f ± %.4f\n', b, sigma_b);
% Optional: Plot the data and the fitted line
x_fit = linspace(min(x), max(x), 100);
y_fit = a * x_fit + b;
figure;
errorbar(x, y, sigma, 'bo', 'MarkerFaceColor', 'b'); hold on;
plot(x_fit, y_fit, 'r-', 'LineWidth', 2);
xlabel('x'); ylabel('y');
title('Weighted Least Squares Linear Fit');
legend('Data with Error Bars', 'Fitted Line');
grid on;
🔍 Explanation:
A is the design matrix: each row corresponds to a data point, and the columns represent the coefficients (x and constant).
W is the weight matrix, where entries are the inverse variances: ( w_i = 1/\sigma_i^2 )
- The solution is found by solving the normal equations:
[
\boldsymbol{\beta} = (A^T W A)^{-1} A^T W y
]
- The covariance matrix of the estimates gives the estimated uncertainties for
a and b.
📌 Tip:
You can wrap this into a function for reusability. Here's a simple start:
function [a, b, sigma_a, sigma_b] = weighted_linear_fit(x, y, sigma)
x = x(:); y = y(:); sigma = sigma(:);
A = [x, ones(size(x))];
W = diag(1 ./ sigma.^2);
Cov_beta = inv(A' * W * A);
beta = Cov_beta * (A' * W * y);
a = beta(1);
b = beta(2);
sigma_a = sqrt(Cov_beta(1,1));
sigma_b = sqrt(Cov_beta(2,2));
end
Then call it like:
[a, b, sigma_a, sigma_b] = weighted_linear_fit(x, y, sigma);
Let me know if you want to expand this to support error in x as well (Total Least Squares or Deming regression).