Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply two vector and get a matrix?

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?

like image 795
Larry Avatar asked Feb 18 '15 07:02

Larry


People also ask

How do you multiply two vectors in a matrix?

First, multiply Row 1 of the matrix by Column 1 of the vector. Next, multiply Row 2 of the matrix by Column 1 of the vector. Finally multiply Row 3 of the matrix by Column 1 of the vector.

Does multiplying two vectors give a matrix?

Unlike the inner product, the outer product of two vectors produces a rectangular matrix, not a scalar.


1 Answers

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]]) 
like image 88
Dietrich Epp Avatar answered Oct 14 '22 00:10

Dietrich Epp