clc clear all x = [0 0.5 1 1.5 2 2.5]; y = [0.4326 -0.1656 3.1253 4.7877 4.8535 8.6909]; n = 6; xi = 0; yi = 0; xiyi = 0; xisqr = 0; for i = 1:n xi = xi + x(i); yi = yi + y(i); xiyi = xiyi + x(i) * y(i); xisqr = xisqr + (x(i))^2; end a = (n * xiyi - xi * yi) / (n * xisqr - xi^2); b = (xisqr * yi - xi * xiyi) / ((n * xisqr) - (xi^2)); fx = a * x + b; error = 0; for i = 1:n error = error + (y(i) - (a * x(i) + b)) ^ 2; end plot(x, y, 'bo', x, fx, 'r-'); xlabel('x'); ylabel('y'); title('Linear Regression'); legend('Original Data', 'Fitted Line'); disp(['Sum of squared errors: ', num2str(error)]);