Search code examples
pythonnumpymatrixcomplex-numbers

How does NumPy multiply matrices of complex numbers?


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?


Solution

  • 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.