timakro timakro - 1 year ago 85
Python Question

Generate a two dimensional array of complex numbers

I want to generate a two dimensional array of a given size containing complex numbers like in this example:

>>> generate_array((2, 3))
array([[ 0.+0.j, 1.+0.j, 2.+0.j],
[ 0.+1.j, 1.+1.j, 2.+1.j]])

Answer Source

Here is a way to achieve this
using np.indices() engaged with np.vectorize():

def generate_array(dim):
    X, Y = np.indices(dim)
    return np.array(np.vectorize(complex)(X, Y))

ar = generate_array((2, 3))


[[ 0.+0.j  0.+1.j  0.+2.j]
 [ 1.+0.j  1.+1.j  1.+2.j]]