%% Simple linear regression. Generate some linear data, add normally distributed noise, and compute the coefficients by solving the normal equations. %% Specify model parameters a = 1; b = 2; %% Generate some data x = (1:10)'; yTrue = a + b*x; %% Add normal error to simulate experimental noise NoiseStd = 0.5; % The standard deviation of the noise err = NoiseStd*randn(length(x), 1); yExpt = yTrue + err; %% Create design matrix A = [ones(size(x)) x]; %% Solve normal equation using the MATLAB backslash operator betaHat = A \ yExpt %% Plot data and fit plot(x, yExpt, 'ro', 'MarkerSize', 8) hold on xFit = (1:0.1:10)'; yFit = [ones(size(xFit)) xFit]*betaHat; plot(xFit, yFit, 'b-', 'LineWidth', 2) xlim([0, 11]) ylim([0, 23]) xlabel('x') ylabel('y') grid on legend('Data', 'Fit', 'Location', 'NW')