function [b, stats] = weighted_least_squares(x, y, sigma)
% WEIGHTED_LEAST_SQUARES Performs linear regression with known measurement errors
%
% Inputs:
% x: Independent variable values
% y: Dependent variable values
% sigma: Standard deviation for each y measurement
%
% Outputs:
% b: Regression coefficients [intercept; slope]
% stats: Structure with additional statistics
% Convert inputs to column vectors
x = x(:); y = y(:); sigma = sigma(:);
% Calculate weights (inverse variance)
weights = 1 ./ (sigma.^2);
% Design matrix
X = [ones(length(x), 1), x];
% WLS solution: b = (X'WX)^(-1)X'Wy
W = diag(weights);
b = (X' * W * X) \ (X' * W * y);
% Calculate fitted values and residuals
fitted = X * b;
residuals = y - fitted;
% Calculate statistics
if nargout > 1
weighted_residuals = sqrt(weights) .* residuals;
sse = sum(weights .* residuals.^2);
dof = length(y) - 2; % Degrees of freedom
s2 = sse / dof; % Estimated error variance
% Parameter covariance matrix
cov_b = s2 * inv(X' * W * X);
% Standard errors
se_b = sqrt(diag(cov_b));
% Calculate R-squared
weighted_mean = sum(weights .* y) / sum(weights);
ss_total = sum(weights .* (y - weighted_mean).^2);
r_squared = 1 - (sse / ss_total);
% Store statistics
stats.residuals = residuals;
stats.weighted_residuals = weighted_residuals;
stats.standard_errors = se_b;
stats.r_squared = r_squared;
stats.covariance = cov_b;
end
end
% Example usage (can be saved as a separate script)
function demo_wls()
% Generate sample data with heteroscedastic errors
n = 50;
x = linspace(0, 10, n)';
true_slope = 2;
true_intercept = 5;
% Standard deviations increase with x
sigma = 0.5 + 0.3*x;
rng(42); % For reproducibility
y = true_intercept + true_slope*x + randn(n,1).*sigma;
% Perform WLS regression
[b_wls, stats_wls] = weighted_least_squares(x, y, sigma);
% Ordinary least squares for comparison
b_ols = polyfit(x, y, 1);
b_ols = flip(b_ols)'; % [intercept; slope]
% Plot results
figure;
errorbar(x, y, sigma, 'o', 'Color', [0.7 0.7 1]);
hold on;
grid on;
% Plot regression lines
x_line = [min(x); max(x)];
plot(x_line, b_wls(1) + b_wls(2)*x_line, 'r-', 'LineWidth', 2);
plot(x_line, b_ols(1) + b_ols(2)*x_line, 'g--', 'LineWidth', 2);
plot(x_line, true_intercept + true_slope*x_line, 'k:', 'LineWidth', 1.5);
legend('Data with errors', 'Weighted Least Squares', ...
'Ordinary Least Squares', 'True line');
title('Weighted vs. Ordinary Least Squares');
xlabel('x'); ylabel('y');
fprintf('True model: y = %.2f + %.2f*x\n', true_intercept, true_slope);
fprintf('WLS model: y = %.4f + %.4f*x (SE slope: %.4f)\n', ...
b_wls(1), b_wls(2), stats_wls.standard_errors(2));
fprintf('OLS model: y = %.4f + %.4f*x\n', b_ols(1), b_ols(2));
fprintf('WLS R-squared: %.4f\n', stats_wls.r_squared);
end
Would you like me to explain or break down the code?