1

I'd like to know how to make a simple data cube (matrix) with three 1D arrays or if there's a simpler way. I want to be able to call a specific value at the end from the cube such as cube[0,2,6].

x = arange(10)
y = arange(10,20,1)
z = arange(20,30,1)

cube = meshgrid(x,y,z)

But this doesn't give the desired result, as it gives mulitple arrays and can't call a specific number easily. I'd like to be able to use this for large data sets that would be laborious to do by hand, later on. Thanks

2
  • I'd rather want to be able to put my own numbers in so it'd look less like a sequence Commented Mar 10, 2017 at 3:05
  • Then just fill it... a = np.arange(27).reshape(3, 3, 3) ... or whatever, then ... a.fill(0) Commented Mar 10, 2017 at 3:12

1 Answer 1

2

meshgrid as its name suggests creates an orthogonal mesh. If you call it with 3 arguments it will be a 3d mesh. Now the mesh is 3d arrangement of points but each point has 3 coordinates. Therefore meshgrid returns 3 arrays one for each coordinate.

The standard way of getting one 3d array out of that is to apply a vectorised function with three arguments. Here is a simple example:

>>> x = arange(7)
>>> y = arange(0,30,10)
>>> z = arange(0,200,100)
>>> ym, zm, xm = meshgrid(y, z, x)
>>> xm
array([[[0, 1, 2, 3, 4, 5, 6],
        [0, 1, 2, 3, 4, 5, 6],
        [0, 1, 2, 3, 4, 5, 6]],

       [[0, 1, 2, 3, 4, 5, 6],
        [0, 1, 2, 3, 4, 5, 6],
        [0, 1, 2, 3, 4, 5, 6]]])
>>> ym
array([[[ 0,  0,  0,  0,  0,  0,  0],
        [10, 10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20, 20]],

       [[ 0,  0,  0,  0,  0,  0,  0],
        [10, 10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20, 20]]])
>>> zm
array([[[  0,   0,   0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0,   0,   0]],

       [[100, 100, 100, 100, 100, 100, 100],
        [100, 100, 100, 100, 100, 100, 100],
        [100, 100, 100, 100, 100, 100, 100]]])
>>> cube = xm + ym + zm
>>> cube
array([[[  0,   1,   2,   3,   4,   5,   6],
        [ 10,  11,  12,  13,  14,  15,  16],
        [ 20,  21,  22,  23,  24,  25,  26]],

       [[100, 101, 102, 103, 104, 105, 106],
        [110, 111, 112, 113, 114, 115, 116],
        [120, 121, 122, 123, 124, 125, 126]]])
>>> cube[0, 2, 6]
26
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.