-3

I noticed that in python for a vector, it does not matter the order you transpose it when calculating the inner product. Is this a bug?

If u is a series

import numpy as np
u = np.array([0,1,1,1])
u.T @ u

returns a scalar as it should.

But also,

u @ u.T

Is also returning a scalar. Any ideas of what could be going on?

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 2
    Have you looked at the shape of `u.T` compared to `u` here? [Transposing a 1D NumPy array](https://stackoverflow.com/questions/5954603/transposing-a-1d-numpy-array) might be helpful. – Mark Sep 05 '22 at 04:02

1 Answers1

2

In numpy, if you intend to do linear algebra operations, you need to make 2-dimensional arrays. Your example above is 1-dim, so it is not recognized as a matrix.

There is still a "matrix" object in the numpy linalg library but it is deprecated, I believe, and the best way is just to make (or reshape) arrays into 2-d objects if you intend to do linear algebra

In [36]: import numpy as np

In [37]: u = np.array([1, 0, 2])

In [38]: u.T
Out[38]: array([1, 0, 2])

In [39]: u = u.reshape((1,3))

In [40]: u.T
Out[40]: 
array([[1],
       [0],
       [2]])

In [41]: u @ u.T
Out[41]: array([[5]])

In [42]: u.T @ u
Out[42]: 
array([[1, 0, 2],
       [0, 0, 0],
       [2, 0, 4]])
AirSquid
  • 10,214
  • 2
  • 7
  • 31