views:

224

answers:

1

I swear this should be so easy... Why is it not? :(

In fact, I want to combine 2 parts of the same array to make a complex array:

Data[:,:,:,0] , Data[:,:,:,1]

These don't work:

x = np.complex(Data[:,:,:,0], Data[:,:,:,1])
x = complex(Data[:,:,:,0], Data[:,:,:,1])

Am I missing something? Does numpy not like performing array functions on complex numbers? Here's the error:

TypeError: only length-1 arrays can be converted to Python scalars

Cheers

+4  A: 

This seems to do what you want:

numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)

Here is another solution:

numpy.vectorize(complex)(Data[:,:,:,0], Data[:,:,:,1])

And yet another simpler solution:

Data[:,:,:,0] + 1j * Data[:,:,:,1]
EOL
Same error I'm afraid: TypeError: only length-1 arrays can be converted to Python Scalars
Duncan Tait
@Duncan: I updated the original answer after performing the test. It seems to be working, now.
EOL
@EOL, thanks alot that does work. It's VERY slow though (as you might expect - as it's not really a numpy function), it takes 5 seconds per loop now instead of 0.1
Duncan Tait
@Duncan: I added two other solutions: it may be worth to time them too. If this works for you, please thumb up the answer!
EOL
Excellent they're both much faster :)
Duncan Tait