I am trying to multiply two numpy arrays as matrices. I expect that if A
is an n x m
matrix and B
is an m x p
matrix, then A*B
yields an n x p
matrix.
This code creates a 5x3 matrix and a 3x1 matrix, as verified by the shape
property. I was careful to create both arrays in two dimensions. The final line performs the multiplication, and I expect a 5x1 matrix.
A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
print(A)
print(A.shape)
B = np.array([[2],[3],[4]])
print(B)
print(B.shape)
print(A*B)
Result
[[1 1 1]
[2 2 2]
[3 3 3]
[4 4 4]
[5 5 5]]
(5, 3)
[[2]
[3]
[4]]
(3, 1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-38-653ff6c66fb7> in <module>()
5 print(B)
6 print(B.shape)
----> 7 print(A*B)
ValueError: operands could not be broadcast together with shapes (5,3) (3,1)
Even the exception message indicates that the inner dimensions (3 and 3) match. Why did multiplication throw an exception? How should I generate a 5x1 matrix?
I am using Python 3.6.2 and Jupyter Notebook server 5.2.2.