In ordinary least squares linear regression, given a set of data points $(x_1,y_1),(x_2,y_2),...(x_N,y_N)$, that we want to fit to the function $y=\beta_0 + \beta_1 x$, we would usually write the linear model as the matrix equation $$ \begin{align} \mathbf{Y} &= \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon} \\ \begin{pmatrix} y_1 \\ y_2 \\ \vdots \\ y_N \end{pmatrix} &= \begin{pmatrix} 1 & x_1 \\ 1 & x_2 \\ \vdots & \vdots \\ 1 & x_N \end{pmatrix} \cdot \begin{pmatrix} \beta_0 \\ \beta_1\end{pmatrix} + \begin{pmatrix} \varepsilon_1 \\ \varepsilon_2 \\ \vdots \\ \varepsilon_N \end{pmatrix} \end{align} \tag{1} $$ where $\beta_0$ and $\beta_1$ are the intercept and slope of the model, respectively, and $\varepsilon_k$ are the residuals between the model and each data point.
Minimizing the sum of the squares of these residuals (by differentiating with respect to $\boldsymbol{\beta}$ and setting the result equal to zero) then gives the equation $$ \mathbf{X}^\textrm{T} \mathbf{Y} = (\mathbf{X}^\textrm{T}\mathbf{X})\boldsymbol{\beta} \tag{2} $$ and so the typical equation to solve to find the best fit parameters is $$ \boldsymbol{\beta} = (\mathbf{X}^\textrm{T}\mathbf{X})^{-1}\mathbf{X}^\textrm{T}\mathbf{Y} \tag{3} $$ (for example, see this link).
This is fine for me so far.
However, I am confused that it seems like the exact same result is obtained by solving instead
$$
\mathbf{Y} = \mathbf{X}\boldsymbol{\beta} \tag{4}
$$
The following Matlab script illustrates this, where the outputs for beta1
and beta2
are identical:
x_data = [0.1 ; 3.6 ; 5.2 ; 8.1];
y_data = [0.15 ; 3.5 ; 5.4 ; 7.6];
X = [ones(length(x_data),1) x_data];
Y = y_data;
% First method
beta1 = (X.'*X) \ (X.'*Y); % instead of backslash, can also do beta = inv(X.'*X)*(X.')*Y;
% Second method
beta2 = X \ Y;
Equation (2) arises from minimizing the residuals, whereas Eq. (4) seems to have just neglected the residuals altogether?
Is it as simple as the fact that the $\mathbf{X}^\textrm{T}$ can simply cancel on both sides of Eq. (2)? In which case, why do we see the form given in Eq. (2) used so much?
(It is obviously much more computationally expensive to do method 1, compared with method 2.)
What am I missing here?
Thanks