%Example 1 using the normal equation x=[2 5 7 8]'; y=[1 2 3 3]'; numpts=length(x); % This is how many data points we have A=[x ones(numpts,1)]; % Build the matrix A c=inv(A'*A)*A'*y; % c is the least squares slope/intercept fprintf('The slope is: %f, the intercept is: %f\n',c(1),c(2)); %Computing the error between y and the values on the line: Err=norm(y-A*c); fprintf('The error is: %f\n',Err); xTest=linspace(0,8); %Create test data yTest=c(1)*xTest+c(2); %Create the line using the test data plot(x,y,'k*',xTest,yTest,'k-'); % Plot the data with the line