Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert variable step into Numpy mgrid?

Tags:

python

numpy

I am trying to use numpy.mgrid to create two grid arrays, but I want a way to insert a variable as the number of steps.

Without a variable number of steps, numpy.mgrid works as expected with this code:

x, y = np.mgrid[0:1:3j, 0:2:5j]

But, what I want is something like this, because I am not able to explicitly state my step number in the line of code to generate the grid arrays (the values may change due to other processes in my script):

num_x_steps = 3
num_y_steps = 5
x, y = np.mgrid[0:1:(num_x_steps)j, 0:2:(num_y_steps)j] #Try convert to complex

Is there a way to do that, that returns a result equivalent to the first method?

I tried running my 3-line code with and without parentheses and tried a couple other modifications, but nothing seemed to work.

NOTE: I tried reading this topic, but I am not sure if what that topic deals with is applicable to this problem; I don't quite understand what is being asked or how it was answered. (Also, I tried running the line of code from the answer, and it returned a MemoryError.) If said topic does answer my problem, could someone please explain it better, and how it applies to my problem?

like image 524
Johiasburg Frowell Avatar asked Jul 01 '15 14:07

Johiasburg Frowell


2 Answers

The glitch is that j following parentheses doesn't convert to a complex number.

In [41]:(1)j
  File "<ipython-input-41-874f75f848c4>", line 1
    (1)j
       ^
  SyntaxError: invalid syntax

Multiplying a value by 1j will work, and these lines give x, y equivalent to your first line:

num_x_steps = 3
num_y_steps = 5
x, y = np.mgrid[0:1:(num_x_steps * 1j), 0:2:(num_y_steps * 1j)]
like image 141
Sean Easter Avatar answered Sep 29 '22 08:09

Sean Easter


I think what you are looking for is to convert the num of steps to a complex number.

num_x_steps = 3
x_steps = complex(str(num_x_steps) + "j")

num_y_steps = 5
y_steps = complex(str(num_y_steps) + "j")

x, y = np.mgrid[0:1:x_steps, 0:2:y_steps]
like image 37
Dobz Avatar answered Sep 29 '22 09:09

Dobz