'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?
Solution 1:[1]
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 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Serenity |
