3
votes

I have a numpy array of complex numbers. I seek to clip the real and imaginary parts of each number in the array to some prescribed minimum and maximum (same clipping applied to both the real and imaginary parts). For example, consider:

import numpy as np

clip_min = -4
clip_max = 3

x = np.array([-1.4 + 5j, -4.7 - 3j])

The desired output of the clipping operation would be:

[-1.4 + 3j, -4-3j]

I can achieve this by calling np.clip on the real and imaginary parts of the complex array and then adding them (after multiplying the imaginary clipped data by 1j). Is there a way to do this with one command?

np.clip(x, clip_min, clip_max) 

doesn't yield the desired result.

1

1 Answers

2
votes

There is a slightly more efficient way than clipping the real and imaginary parts as separate arrays, using in-place operations:

np.clip(x.real, clip_min, clip_max, out=x.real)
np.clip(x.imag, clip_min, clip_max, out=x.imag)

If these are just cartesian coordinates stored in complex numbers, you could clip them in a single command by keeping them as floats rather than complex.

x = array([[-1.4,  5. ],
           [-4.7, -3. ]])
np.clip(x, clip_min, clip_max)
>>> array([[-1.4,  3. ],
           [-4. , -3. ]])