How to make 2d complex number array in numpy?

I would like to make a 2d array of even distribution of complex numbers, a part of complex plane, for example (-1, 1i), (-1, -1i), (1, 1i), (1, -1i) with 20 numbers in each dimension.

I know I can do this for complex numbers in 1 d with np.linspace like this:

import numpy as np

complex_array = np.linspace(0, complex(1, 1), num = 11)
print(complex_array)

[0. +0.j, 0.1+0.1j, 0.2+0.2j, 0.3+0.3j, 0.4+0.4j,
 0.5+0.5j, 0.6+0.6j, 0.7+0.7j, 0.8+0.8j, 0.9+0.9j, 1. +1.j ]

But I can’t get my head around how to produce this in two dimensions to get a part of a complex plane?

Some somewhat similar questions mention np.mgrid, but the examples are with reals and I would like the array to contain dtype=complex so my math keeps simple.

Maybe I am just missing something, and perhaps just a simple example would explain a lot..

>Solution :

You can use broadcasting to do that. For example:

result = np.linspace(0, 1j, num = 11).reshape(-1, 1) + np.linspace(0, 1, num = 11)

Using meshgrid also works but it is likely slower:

a, b = np.meshgrid(np.linspace(0, 1, num = 11), np.linspace(0, 1j, num = 11))
result = a + b

Leave a Reply