Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

python - Is there a multi-dimensional version of arange/linspace in numpy?

I would like a list of 2d NumPy arrays (x,y) , where each x is in {-5, -4.5, -4, -3.5, ..., 3.5, 4, 4.5, 5} and the same for y.

I could do

x = np.arange(-5, 5.1, 0.5)
y = np.arange(-5, 5.1, 0.5)

and then iterate through all possible pairs, but I'm sure there's a nicer way...

I would like something back that looks like:

[[-5, -5],
 [-5, -4.5],
 [-5, -4],
 ...
 [5, 5]]

but the order does not matter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use np.mgrid for this, it's often more convenient than np.meshgrid because it creates the arrays in one step:

import numpy as np
X,Y = np.mgrid[-5:5.1:0.5, -5:5.1:0.5]

For linspace-like functionality, replace the step (i.e. 0.5) with a complex number whose magnitude specifies the number of points you want in the series. Using this syntax, the same arrays as above are specified as:

X, Y = np.mgrid[-5:5:21j, -5:5:21j]

You can then create your pairs as:

xy = np.vstack((X.flatten(), Y.flatten())).T

As @ali_m suggested, this can all be done in one line:

xy = np.mgrid[-5:5.1:0.5, -5:5.1:0.5].reshape(2,-1).T

Best of luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...