Reputation: 11
I got some output of my program, say
a = [0.5 0.73 -0.48]
(I don't see commas there, which I feel a bit weird)
b = [0.1 0.2 0.3 0.4 0.5]
(same as above)
I checked each by using type() and they were numpy.ndarray, I then use len() to verify their size and got 3 and 5 respectively. I also did shape to find that a is (3,) and b is (5,)
Now, I wonder how could I multiply these two to get a matrix of size 3 by 5?
I have tried so many ways and none has worked.
Upvotes: 1
Views: 191
Reputation: 91
Try the outer product: https://numpy.org/doc/stable/reference/generated/numpy.outer.html
import numpy as np
a = np.array([0.5, 0.73, -0.48])
b = np.array([0.1, 0.2, 0.3, 0.4, 0.5])
result = np.outer(a, b)
print(result)
Output:
[[ 0.05 , 0.1 , 0.15 , 0.2 , 0.25 ],
[ 0.073, 0.146, 0.219, 0.292, 0.365],
[-0.048, -0.096, -0.144, -0.192, -0.24 ]]
Upvotes: 2
Reputation: 54867
You don't see commas because those are numpy vectors. Numpy displays its arrays without commas.
The "@" operator is matrix multiply. The key is that you need to turn these into 2D arrays.
import numpy as np
a = np.array([0.5, 0.73, -0.48])
b = np.array([0.1, 0.2, 0.3, 0.4, 0.5])
result = a.reshape(3,1)@b.reshape(1,5)
print(result)
output:
[[ 0.05 0.1 0.15 0.2 0.25 ]
[ 0.073 0.146 0.219 0.292 0.365]
[-0.048 -0.096 -0.144 -0.192 -0.24 ]]
Upvotes: 1