Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 837
Hilemonstoer Avatar asked Aug 25 '15 15:08

Hilemonstoer


People also ask

What is the difference between numpy Linspace and arange?

arange function. The essential difference between NumPy linspace and NumPy arange is that linspace enables you to control the precise end value, whereas arange gives you more direct control over the increments between values in the sequence.

Does numpy have Linspace?

linspace is an in-built function in Python's NumPy library. It is used to create an evenly spaced sequence in a specified interval.

Can numpy arrays be multidimensional?

In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.

What does the numpy Linspace () function do?

linspace. Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval [start, stop].


1 Answers

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!

like image 108
farenorth Avatar answered Sep 22 '22 18:09

farenorth