Scale the real part of the numpy complex matrix

I have a vector of complex numbers (the result of an FFT), and I would like to scale only the real part of complex numbers by factors in another vector.

Example

cplxarr= np.array([1+2j, 3+1j, 7-2j]) factarr= np.array([.5, .6, .2]) # desired result of cplxarr * factarr : # np.array([.5+2j 1.8+1j 1.4-2j]) 

(Yes, we are talking about the frequency response of human hearing in a very specific setting.)
Obviously, multiplication with the above vectors also scales the imaginary parts.

How to configure factarr and what operation should I perform to achieve the desired result? If at all possible, that is, without separating the real and imaginary parts, scaling the real parts and reassembling as a new complex vector.

+4
source share
1 answer

This will do the following:

 >>> factarr*cplxarr.real + (1j)*cplxarr.imag array([ 0.5+2.j, 1.8+1.j, 1.4-2.j]) 

Not sure if this is the best way.


It turns out that for me at least (OS-X 10.5.8, python 2.7.3, numpy 1.6.2) This version is about two times faster than the other version that uses np.vectorize :

 >>> from timeit import timeit >>> timeit('factarr*cplxarr.real+(1j)*cplxarr.imag',setup='from __main__ import factarr,cplxarr') 21.008132934570312 >>> timeit('f(cplxarr.real * factarr, cplxarr.imag)',setup='from __main__ import factarr,cplxarr; import numpy as np; f=np.vectorize(np.complex)') 46.52931499481201 

This doesn't seem to make much difference for using np.complex and complex provided by python:

 >>> timeit('f(cplxarr.real * factarr, cplxarr.imag)',setup='from __main__ import factarr,cplxarr; import numpy as np; f=np.vectorize(complex)') 44.87726283073425 

CURRENT LEADER UNDER TIME (proposed by eryksun in the comments below)

 >>> timeit.timeit('a = cplxarr.copy(); a.real *= factarr ',setup='from __main__ import factarr,cplxarr') 8.336654901504517 

And the proof that it works:

 >>> a = cplxarr.copy() >>> a.real *= factarr >>> a array([ 0.5+2.j, 1.8+1.j, 1.4-2.j]) 

This will obviously be even faster if you want to perform the operation in place (and therefore leave it inactive).

+8
source

All Articles