Assigning complex values to numpy arrays?
Actually, none of the proposed solutions worked in my case (Python 2.7.6, NumPy 1.8.2).
But I've found out, that change of dtype
from complex
(standard Python library) to numpy.complex_
may help:
>>> import numpy as np
>>> x = 1 + 2 * 1j
>>> C = np.zeros((2,2),dtype=np.complex_)
>>> C
array([[ 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j]])
>>> C[0,0] = 1+1j + x
>>> C
array([[ 2.+3.j, 0.+0.j],
[ 0.+0.j, 0.+0.j]])
To insert complex x
or x + something
into C
, you apparently need to treat it as if it were an array, so either index into x
or assign it to a slice of C
:
>>> C
array([[ 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j]])
>>> C[0, 0:1] = x
>>> C
array([[ 0.47229555+0.7957525j, 0.00000000+0.j ],
[ 0.00000000+0.j , 0.00000000+0.j ]])
>>> C[1, 1] = x[0] + 1+1j
>>> C
array([[ 0.47229555+0.7957525j, 0.00000000+0.j ],
[ 0.00000000+0.j , 1.47229555+1.7957525j]])
It looks like NumPy isn't handling this case correctly. Consider submitting a bug report.