# [SciPy-user] Create n-dim array from axis

josef.pktd@gmai... josef.pktd@gmai...
Tue Mar 24 09:56:53 CDT 2009

```On Tue, Mar 24, 2009 at 7:43 AM, Vincent Schut <schut@sarvision.nl> wrote:
> josef.pktd@gmail.com wrote:
>> On Mon, Mar 23, 2009 at 10:07 AM, Paul Hilscher
>> <p.hilscher@lsw.uni-heidelberg.de> wrote:
>>>> try mx, my = numpy.meshgrid(x, y)
>>>> [zip(a,b) for (a,b) in zip(mx, my)]HTH,
>>> Thanks a lot David, this works perfectly fine for 2-dimensions.
>>> Is there any possibility to extend it to 3-dimensions with axis z, or
>>> even to 4-dimensions giving axis w ?
>>>
>>> Thanks again,
>>>
>>> Paul
>>
>> I would also like to know what an efficient way is to do this. For
>> arbitrary dimension, I never found anything except for a brute force
>> loop or recursive function.
>>
> Would this do? Should work with arbitrary number of dimensions.
>
> def create_array(startStopStep):
>     # startStopStep is a tuple/list of (start,stop,step) entities to
>     # define the axes
>     slices = [slice(start, stop, complex(0, step)) for
> (start,stop,step) in startStopStep]
>     g = numpy.mgrid[slices].transpose()
>     return g
>
> print create_array(((0,1,3), (2,3,3)))
>
> [[[ 0.   2. ]
>   [ 0.5  2. ]
>   [ 1.   2. ]]
>
>  [[ 0.   2.5]
>   [ 0.5  2.5]
>   [ 1.   2.5]]
>
>  [[ 0.   3. ]
>   [ 0.5  3. ]
>   [ 1.   3. ]]]
>
> Regards,
> Vincent.
>

This is a good example for using slices and mgrid and is much better
for regularly spaced grids (representable of slices) than what I had.
However, what I also needed in the past was building a grid for
arbitrary points in each dimension

x = [2, 3, 5, 10]
y = [0, 1]
z = [100, 200, 500, 1000]
create_array(x, y, z)
?

Your function is also useful to get all combinations into a 2d array:
>>> create_array(((0,1,2), (2,3,3), (1,5,2))).T.reshape(3,-1).T
array([[ 0. ,  2. ,  1. ],
[ 0. ,  2. ,  5. ],
[ 0. ,  2.5,  1. ],
[ 0. ,  2.5,  5. ],
[ 0. ,  3. ,  1. ],
[ 0. ,  3. ,  5. ],
[ 1. ,  2. ,  1. ],
[ 1. ,  2. ,  5. ],
[ 1. ,  2.5,  1. ],
[ 1. ,  2.5,  5. ],
[ 1. ,  3. ,  1. ],
[ 1. ,  3. ,  5. ]])
>>> create_array(((0,1,2), (2,3,3))).T.reshape(2,-1).T
array([[ 0. ,  2. ],
[ 0. ,  2.5],
[ 0. ,  3. ],
[ 1. ,  2. ],
[ 1. ,  2.5],
[ 1. ,  3. ]])

Thanks,
Josef
```