Search code examples
pythonnumpycomplex-numbers

numpy.minimum for complex numbers


numpy.minimum does not seem to work for complex numbers:

np.minimum(5+3*1j,4+30*1j)
(4+30j)

I want to keep the value with the maximum magnitude. It only compares the real part. Any other function for elementwise minimum comparison? MATLAB min does work with complex numbers. Thanks


Solution

  • You can use np.where and np.abs

    Suppose you have

    vals1 = [4+30*1j, 7+3*1j, 4+30*1j]
    vals2 = [5+3*1j, 6+3*1j, 5+3*1j]
    

    then

    >>> np.where(np.abs(vals1) > np.abs(vals2), vals2, vals1)
    array([5.+3.j, 6.+3.j, 5.+3.j])