Reputation: 759
I have a binary file written as
16b-Real (little endian, 2s compliment)
16b-Imag (little endian, 2s compliment)
.....repeating
I need to convert it to a 1D array of complex numbers. Can't figure out how to combine the "tuples or lists" into a single value
import numpy as np
dtype = np.dtype([('i','<i2'), ('q','<i2')])
array = np.fromfile(data_file, dtype=dtype)
print(array)
el = array[0]
print(el)
print(type(el))
Output:
[(531, -660) (267, -801) (-36, -841) ... (835, -102) (750, -396)
(567, -628)]
(531, -660)
<class 'numpy.void'>
Hoping for output:
[531-660j, 267-801j,...]
Upvotes: 1
Views: 1512
Reputation: 231385
So you have loaded the file as a structured array with 2 integer fields:
In [71]: dtype = np.dtype([('i','<i2'), ('q','<i2')])
In [72]: arr = np.array([(531, -660), (267, -801), (-36, -841), (835, -102), (750, -396)], dtype)
In [73]: arr
Out[73]:
array([(531, -660), (267, -801), (-36, -841), (835, -102), (750, -396)],
dtype=[('i', '<i2'), ('q', '<i2')])
We can add the two fields with the appropriate 1j
multiplier to make a complex array:
In [74]: x=arr['i']+1j*arr['q']
In [75]: x
Out[75]: array([531.-660.j, 267.-801.j, -36.-841.j, 835.-102.j, 750.-396.j])
If I'm not mistaken, numpy
only implements float complex (64 and 128 bit), so probably have go through this <i2
stage.
Upvotes: 1
Reputation: 20490
You can convert each tuple to a complex number while iterating over the list of tuples
array = [(531, -660), (267, -801), (-36, -841) ,(835, -102) ,(750, -396), (567, -628)]
#Iterate over each element and convert it to complex
array = [complex(*item) for item in array]
print(array)
print(type(array[0]))
The output will be
[(531-660j), (267-801j), (-36-841j), (835-102j), (750-396j), (567-628j)]
<class 'complex'>
Upvotes: 3