How to multiply two vector and get a matrix?

46,797

Solution 1

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]])

Solution 2

Function matmul (since numpy 1.10.1) works fine:

import numpy as np

a = np.array([[1],[2],[3],[4]])
b = np.array([[1,1,1,1,1],])

ab = np.matmul(a, b)
print (ab)
print(ab.shape)

You have to declare your vectors right. The first has to be a list of lists of one number (this vector has to have columns in one row), and the second - a list of list (this vector has to have rows in one column) like in above example.

Output:

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

(4, 5)

Solution 3

If you are using numpy.

First, make sure you have two vectors. For example, vec1.shape = (10, ) and vec2.shape = (26, ); in numpy, row vector and column vector are the same thing.

Second, you do res_matrix = vec1.reshape(10, 1) @ vec2.reshape(1, 26) ;.

Finally, you should have: res_matrix.shape = (10, 26).

numpy documentation says it will deprecate np.matrix(), so better not use it.

Share:
46,797
Larry
Author by

Larry

Updated on July 09, 2022

Comments

  • Larry
    Larry almost 2 years

    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?