Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shortcut to split "complex array" into "real" and "imaginary" arrays

Tags:

python

numpy

let's say I have a numpy array:

import numpy as np

x = np.array((1 + 2j, 2 + 4j, 5 + 10j))

and I want to create two separate arrays, one of the real component, and one with the complex number component without the j. Is there a shortcut to perform this operation in python? the only way i can think of doing this is explicitly:

xr = np.zero(len(x))
xi = np.zero(len(x))
for n in range(0, len(x)):
    xr[m] = x[n].real
    xi[m] = x[n].imag

dunno, just seems like there should be a faster way of typing this...

like

xr = x.real?
xi = x.imag?
like image 488
pico Avatar asked Feb 05 '26 21:02

pico


1 Answers

In [145]: x = np.array((1 + 2j, 2 + 4j, 5 + 10j))                                    
In [146]: x                                                                          
Out[146]: array([1. +2.j, 2. +4.j, 5.+10.j])

The real and imag attributes work for the whole array just as well as for elements:

In [147]: x.real                                                                     
Out[147]: array([1., 2., 5.])
In [148]: x.imag                                                                     
Out[148]: array([ 2.,  4., 10.])
In [149]: xr, xc = x.real, x.imag                                                    
In [150]: xr                                                                         
Out[150]: array([1., 2., 5.])
In [151]: xc                                                                         
Out[151]: array([ 2.,  4., 10.])

The view approach that @user3483203 suggests, tells it to interpret the same databuffer as a sequence of two floats:

In [156]: x.view('(2,)float')                                                        
Out[156]: 
array([[ 1.,  2.],
       [ 2.,  4.],
       [ 5., 10.]])
In [157]: np.dtype('(2,)float')                                                      
Out[157]: dtype(('<f8', (2,)))

This notation can be obscure unless you've already worked with structured arrays and compound dtypes.

like image 167
hpaulj Avatar answered Feb 07 '26 09:02

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!