How to multiply two vector and get a matrix?

Larry picture Larry · Feb 18, 2015 · Viewed 33k times · Source

In numpy operation, I have two vectors, let's say vector A is 4X1, vector B is 1X5, if I do AXB, it should result a matrix of size 4X5.

But I tried lot of times, doing many kinds of reshape and transpose, they all either raise error saying not aligned or return a single value.

How should I get the output product of matrix I want?

Answer

Dietrich Epp picture Dietrich Epp · Feb 18, 2015

Normal matrix multiplication works as long as the vectors have the right shape. Remember that * in Numpy is elementwise multiplication, and matrix multiplication is available with numpy.dot() (or with the @ operator, in Python 3.5)

>>> numpy.dot(numpy.array([[1], [2]]), numpy.array([[3, 4]]))
array([[3, 4],
       [6, 8]])

This is called an "outer product." You can get it using plain vectors using numpy.outer():

>>> numpy.outer(numpy.array([1, 2]), numpy.array([3, 4]))
array([[3, 4],
       [6, 8]])