import numpy as np
A = np.random.rand(3, 4) # 3 x 4 matrix
print(A)
[[0.91093404 0.9512029 0.37012699 0.49695407] [0.12733269 0.98029049 0.3460466 0.83258018] [0.44438983 0.89992234 0.74756983 0.10297354]]
B = np.random.rand(4, 2)
print(B)
[[0.56647329 0.45461109] [0.25323378 0.15791856] [0.54631074 0.61116914] [0.55152014 0.21768352]]
Define matrix multiplication of an $M \times K$ matrix $A$ by a $K \times N$ matrix $B$ as the product $AB$, which is an $M \times N$ matrix, where
$AB[i, j] = A[i, :] \cdot B[:, j]$
The element $AB_{ij}$ is the dot product of the $i^{th}$ row of $A$ and the $j^{th}$ column of $B$
Below are a couple of examples
A $5 \times 3$ matrix multiplied by a $3 \times 4$ matrix yields a $5 \times 4$ matrix. For example, row 3, column 4 can be obtained as follows:
Here's an animation showing how to obtain the rest of the rows and columns (Click here to watch a youtube video where you can pause the frames if needed)
A $2 \times 4$ matrix multiplied by a $4 \times 3$ matrix yields a $2 \times 3$ matrix (Click here to watch a version of this video on youtube where you can pause the frames if needed)
def matrixmul(A, B):
M = A.shape[0]
K = A.shape[1]
assert(B.shape[0] == K)
N = B.shape[1]
AB = np.zeros((M, N))
for i in range(M):
for j in range(N):
AB[i, j] = np.sum(A[i, :]*B[:, j])
return AB
AB = matrixmul(A, B)
print(AB)
[[1.23318104 0.89872221] [0.96860695 0.6054249 ] [0.94482312 0.82344624]]
AB2 = np.dot(A, B)
print(AB2)
[[1.23318104 0.89872221] [0.96860695 0.6054249 ] [0.94482312 0.82344624]]