How to multiply two vector and get a matrix? How to multiply two vector and get a matrix? python python

How to multiply two vector and get a matrix?


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


Function matmul (since numpy 1.10.1) works fine:

import numpy as npa = 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)


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.