0

Surprised I can't find this answer, but I am looking to basically create a covariance matrix, but instead of each value being a covariance, I want each cell to be the product of the two vectors. So if I have 1x5 vector, I want to end up with a 5x5 matrix.

For example:

Input:

[1, 2, 3, 4, 5]

Output:

[[ 1,  2,  3,  4,  5],
 [ 2,  4,  6,  8, 10],
 [ 3,  6,  9, 12, 15],
 [ 4,  8, 12, 16, 20],
 [ 5, 10, 15, 20, 25]]

Is there a fast way without building a loop?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

2

Simply use numpy.outer. It computes the outer product of two vectors.

a = np.array([1, 2, 3, 4, 5])
res = np.outer(a,a)
print(res)

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])

Or if you are ok with broadcasting then :

res = a[:,None]*a
print(res)

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])
MSS
  • 3,306
  • 1
  • 19
  • 50