Outer product using numpy/scipy

2019-08-27 12:36发布

I am using Python 2.7, NumPy 1.6.2 and SciPy 0.16.0 to calculate the following.

I have created a Hadamard matrix. I would like to take a vector from it and compute its outer product with itself. Here is my code.

from scipy import linalg
import numpy
from numpy import linalg as np

def test():
    hadamard_matrix = linalg.hadamard(8)
    outer_product_0 = numpy.multiply(hadamard_matrix[0], hadamard_matrix[0].transpose())
    outer_product_1 = numpy.multiply(hadamard_matrix[0].transpose(), hadamard_matrix[0])

    print str(outer_product_0)
    print str(outer_product_1)

Output:

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
>>> import scipytest
>>> scipytest.test()
[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]

You can see that instead of getting a 2X2 matrix I am getting a vector. Am I doing something wrong?

1条回答
▲ chillily
2楼-- · 2019-08-27 13:17

There is an outer-product in numpy, which works exactly how it is specified.

So vector of size n which is outer-producted with itself would result in nxn matrix.

a = [1, 2, 3]
np.outer(a, a)

will give you

array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])
查看更多
登录 后发表回答