I have 2 matrices A and B --> A is 18 x 9 and B is 18 x 1. I need to find matrix C = (A^T A)^(-1)A^T B. Is there an efficient way to do this without doing it manually? Maybe excel or python?
Asked
Active
Viewed 86 times
2
-
2The [NumPy Python library](https://numpy.org) is basically designed for performing various matrix operations, including multiplication, finding the inverse and so on. – ForceBru Oct 06 '22 at 11:16
-
1@callum Of particular interest: [numpy.loadtxt](https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html) to read matrix from text file (such as a csv file) into a python program; the **`@`** operator for matrix multiplication (do not use **`*`**, which is not matrix multiplication but elementwise multiplication); `a.T` for the transpose of matrix `a` (see [this page for the doc](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.T.html#numpy.ndarray.T)) and [numpy.linalg.inv](https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html) for matrix inverse – Stef Oct 06 '22 at 12:42
-
For big matrices I'd suggest trying to rewrite your equation in a form that can be more efficiently computed, but with those small matrices you can just write it directly as `c = inv(a.T @ a) @ a.T @ b` – Stef Oct 06 '22 at 12:44
-
1Although note that if you import `from numpy.linalg import inv, solve`, then `inv(A) @ b` represents the same mathematical formula as `solve(A, b)`, but `solve(A, b)` is preferable. See [Why does numpy.linalg.solve(A,b) offer more precise matrix inversions than numpy.linalg.inv(A)@b?](https://stackoverflow.com/questions/31256252/why-does-numpy-linalg-solve-offer-more-precise-matrix-inversions-than-numpy-li). – Stef Oct 06 '22 at 12:52
-
(So the line of code you should use with python and numpy would be `c = solve(a.T @ a, a.T @ b)`) – Stef Oct 06 '22 at 13:02