Is there an elegant way to find the maximum value in a complex 2D array, returning the actual complex value, not just its magnitude?

51 views Asked by At

max(some2Ddata,key=np.abs) works, but only for 1D complex arrays

np.max(abs(some2Ddata)) returns the magnitude of the max complex value, but not the value itself

I'm expecting:

some2Ddata = ((1+2j, 5+1j), (4+4j, 2+3j))

complexmax(some2Data)

Which should return 4+4j, not 5.657 (and definitely not 5+1j).

I find it hard to believe that there is not a standard built-in for this operation.

1

There are 1 answers

2
jared On

We can write a simple function for this. We can use np.argmax to get the index of the maximum value (which will be based on np.abs). Because np.argmax returns the flattened index, we then use np.unravel_index (as per the np.argmax documentation examples) to get the 2D index. Finally, we use that index on the original array.

import numpy as np

def complex_max(a):
    raveled_index = np.argmax(np.abs(a))
    unraveled_index = np.unravel_index(raveled_index, a.shape)
    return a[unraveled_index]

some2Ddata = np.array([[1+2j, 5+1j], [4+4j, 2+3j]])
res = complex_max(some2Ddata)
print(res)  # (4+4j)