Reputation: 93410
I've been trying to figure out the algorithm behind NumPy's matrix multiplication for complex numbers:
import numpy as np
A = np.array([[17.+0.j, -3.+0.j],
[-7.+0.j, 1.+0.j]])
B = np.array([[ 60.+0.j, -4.+0.j],
[-12.+0.j, 0.+0.j]])
print(A * B)
It outputs:
[[1020.+0.j 12.-0.j]
[ 84.-0.j 0.+0.j]]
The result from a standard matrix multiplication is very different, as you can see by the numbers below, so I'm left wondering what it is exactly that NumPy does:
[[1056.+0.j -68.+0.j]
[-432.+0.j 28.+0.j]]
I've been trying to reproduce their multiplication algorithm using just for
loops but I still haven't found the answer. Any tips?
Upvotes: 3
Views: 10009
Reputation: 93410
Found it! It seems NumPy uses np.multiply()
(element-wise multiplication), hence the different results.
Here is a naive implementation of this function using for
loops:
def np_multiply(X, Y):
height = X.shape[0]
width = X.shape[1]
output = np.empty((height, width), dtype=np.complex128)
for i in range(height):
for j in range(width):
output[i,j] = X[i, j] * Y[i, j]
return output
This post has an interesting discussion on its performance.
Upvotes: 1
Reputation: 4171
When you compute A*B
it's actually multiplying the matrices elementwise, giving you what is called the hadamard product. It isn't matmul. For example (17.+0.j) * (60.+0.j) = 1020.+0.j
, which is the first element in the output. For matrix multiplication use np.dot
or simply the @
operator, ie, A@B
.
Upvotes: 4