Adam - 1 year ago 103

Python Question

I'm converting some Matlab code in Python. I need to do some matrix manipulation. My matrix (A) is (right now) a 65x3 matrix. However, the number of rows is variable depending on what step I'm at in the program.

In Matlab, the code I'm working on is:

`output = inv(A'*A) * A';`

The following Python code reproduces the expected output just fine. I'm just curious if there is a better (more Pythonic, faster, etc) way to do this? I'm trying to stick only to basic Python and numpy.

`output = np.dot(np.linalg.inv(np.dot(np.transpose(A), A)), np.transpose(A))`

Thanks to anyone who is willing to help.

Answer Source

You can use a the `T`

attribute (transposes the array). Also, if using Python 3.5, you can use `@`

for the dot product (see PEP 465 for details).

```
output = np.linalg.inv(A.T @ A) @ A.T
```