Here is a solution in Java that gives you both:

  • from 3D to 1D
  • from 1D to 3D

Below is a graphical illustration of the path I chose to traverse the 3D matrix, the cells are numbered in their traversal order:

Conversion functions:

public int to1D( int x, int y, int z ) {
    return (z * xMax * yMax) + (y * xMax) + x;
}

public int[] to3D( int idx ) {
    final int z = idx / (xMax * yMax);
    idx -= (z * xMax * yMax);
    final int y = idx / xMax;
    final int x = idx % xMax;
    return new int[]{ x, y, z };
}
Answer from Samuel Kerrien on Stack Overflow
๐ŸŒ
MathWorks
mathworks.com โ€บ matlab โ€บ language fundamentals โ€บ matrices and arrays
Multidimensional Arrays - MATLAB & Simulink
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. ... Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
Discussions

c# - How to "flatten" or "index" 3D-array in 1D array? - Stack Overflow
I am trying to flatten 3D array into 1D array for "chunk" system in my game. It's a 3D-block game and basically I want the chunk system to be almost identical to Minecraft's system (however, this i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
numpy - Python 3D Array Indexing - Stack Overflow
In numpy the leading/first dimension is outermost, slowest. Trailing/last is inner, and fastest varying. The default indexing of the array is the same order as indexing the nest list you used to create it. More on stackoverflow.com
๐ŸŒ stackoverflow.com
3D Array as 1D array? - C++ Forum
Calculate the index in a getter. Allocate in the constructor and delete in the destructor. ... It makes the same amount of sense. As long as you treat the dimensions consistently, it doesn't really matter which one is named x, y or z. Encapsulating access to the data structure as htirwin suggests is one way to ensure the dimensions are treated consistently. ... This is false, C++'s implementation of 3D array ... More on cplusplus.com
๐ŸŒ cplusplus.com
3D Array multiplication and indexing
I am working on converting my function in R into the Stan format and I am a little confused on how I should code my 3D array. I need to input data into my 3D array and it must be able to undergo matrix multiplication. Any feed back on how to reformat this function would be helpful, but particularly ... More on discourse.mc-stan.org
๐ŸŒ discourse.mc-stan.org
6
0
July 21, 2021
๐ŸŒ
Python Like You Mean It
pythonlikeyoumeanit.com โ€บ Module3_IntroducingNumpy โ€บ AccessingDataAlongMultipleDimensions.html
Accessing Data Along Multiple Dimensions in an Array โ€” Python Like You Mean It
The output of grades[:, :1] might look somewhat funny. Because the axis-1 slice only includes one column of numbers, the shape of the resulting array is (3, 1). 0 is thus only valid (non-negative) index for axis-1, since there is only one column to specify in the array.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 67944674 โ€บ python-3d-array-indexing
numpy - Python 3D Array Indexing - Stack Overflow
In numpy the leading/first dimension is outermost, slowest. Trailing/last is inner, and fastest varying. The default indexing of the array is the same order as indexing the nest list you used to create it.
๐ŸŒ
Regenerativetoday
regenerativetoday.com โ€บ indexing-and-slicing-of-1d-2d-and-3d-arrays-using-numpy
Indexing and Slicing of 1D, 2D and 3D Arrays Using Numpy โ€“ Regenerative
In the piece of code below, 1 for the lower limit, 6 for the upper limit (for rows we only have row 0 to row 5. But we need to put 6 as the upper limit because if we put the upper limit 6 we will get the elements of index 5) and 2 is the interval. If you notice we need to use the same formula for the column index. ... Letโ€™s make a three dimensional array with this code below.
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ user โ€บ basics.indexing.html
Indexing on ndarrays โ€” NumPy v2.6.dev0 Manual
The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step (\(k\neq0\)). This selects the m elements (in the corresponding dimension) with index values i, i + k, โ€ฆ, i + (m - 1) k where \(m = q + (r\neq0)\) and q and r are the quotient and remainder obtained by dividing j - i by k: j - i = q k + r, so that i + (m - 1) k < j. For example: >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> x[1:7:2] array([1, 3, 5])
Find elsewhere
๐ŸŒ
Pythoninformer
pythoninformer.com โ€บ python-libraries โ€บ numpy โ€บ index-and-slice
PythonInformer - Indexing and slicing numpy arrays
February 4, 2018 - A 3D array is like a stack of matrices: The first index, i, selects the matrix ยท The second index, j, selects the row ยท The third index, k, selects the column ยท Here is the same diagram, spread out a bit so we can see the values: Here is how to index a particular value in a 3D array: print(a3[2, 0, 1]) # 31 ยท
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ general โ€บ 137677
3D Array as 1D array? - C++ Forum
Calculate the index in a getter. Allocate in the constructor and delete in the destructor. ... It makes the same amount of sense. As long as you treat the dimensions consistently, it doesn't really matter which one is named x, y or z. Encapsulating access to the data structure as htirwin suggests is one way to ensure the dimensions are treated consistently. ... This is false, C++'s implementation of 3D array is exactly the same as taking a 1D array and handling the index yourself.
๐ŸŒ
Stan Forums
discourse.mc-stan.org โ€บ modeling
3D Array multiplication and indexing - Modeling - The Stan Forums
July 21, 2021 - I am working on converting my function in R into the Stan format and I am a little confused on how I should code my 3D array. I need to input data into my 3D array and it must be able to undergo matrix multiplication. Any feed back on how to reformat this function would be helpful, but particularly if I should be using real Nf[ , , ] or matrix[ , ] Nf[ ] for my 3D array. functions { do.function(int mesh, int time, int Q, vector dat, vector Fe, real cv_q, real cv, real sigma.p, real R0, real S0,...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ numpy-index-3d-array-with-index-of-last-axis-stored-in-2d-array
Numpy: Index 3D array with index of last axis stored in 2D array - GeeksforGeeks
July 23, 2025 - In this article, we have demonstrated how to index a 3D NumPy array using indices stored in a 2D array. This technique leverages the numpy.take_along_axis function to efficiently select elements from a multidimensional array based on complex indexing conditions.
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 577933-accessing-elements-in-a-3d-matrix-using-linear-indexing
Accessing Elements in a 3D matrix using Linear Indexing ? - MATLAB Answers - MATLAB Central
August 11, 2020 - Of course linear indexing works with 3D arrays, just as the documentation that I linked to clearly states: "Another method for accessing elements of an array is to use only a single index, regardless of the size or dimensions of the array.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ multidimensional-arrays-in-c
Multidimensional Arrays in C - 2D and 3D Arrays - GeeksforGeeks
3 weeks ago - C supports arrays with any number of dimensions. However, 2D and 3D arrays are among the most commonly used. A two-dimensional (2D) array stores elements in rows and columns. It can be visualized as a table where each element is identified by a row index and a column index.
Top answer
1 of 3
11

This depends on that how you want to order your 3D data in 1D array, if you wanted to have indexes in order: Z, Y, X then your 2x2x2 dimensioned 3D data will be stored like this:

index 0: [z=0,y=0,x=0]
index 1: [z=0,y=0,x=1]
index 2: [z=0,y=1,x=0]
index 3: [z=0,y=1,x=1]
index 4: [z=1,y=0,x=0]
index 5: [z=1,y=0,x=1]
index 6: [z=1,y=1,x=0]
index 7: [z=1,y=1,x=1]

DEPTH dimension corresponds to z, HEIGHT to y and WIDTH to x

The index calculation will be: index = HEIGHT*WIDTH*z + WIDTH*y + x.

The x is not multiplied by anything because the next x index is right after the previous one.

If you want to skip one Y row, you have to add whole row WIDTH, in this case 2, for example if you are at index 1, which has z=0,y=0 and x=1 and you add WIDTH=2 to index, you'll get index 3. Only y dimension has increased by 1.

To move from z=0 to z=1, you have to skip 4 indexes (look up at the index listing), the number is HEIGHT*WIDTH (in this example 2*2).

Performance

To gain speed its best to process your 3D data with z,y,x coordinates incrementing in a sequence so you don't have to recalculate the index so often. For example:

int z = 1, y=1, x=0;
int index = HEIGHT*WIDTH*z + WIDTH*y;
int data;

for(x=0;x<WIDTH;x++)
{
    Object obj = oneDArray[index+x];
}

In ideal case, all processing of data is independent from each other and you don't have to even calculate the index, just increment one index trough whole oneDArray. What's possible to precompute depends on your usage.

2 of 3
10

Here is a solution in Java that gives you both:

  • from 3D to 1D
  • from 1D to 3D

My own micro benchmark showed that 1D array is 50% faster to get/set values than through 3D array.

Below is a graphical illustration of the path I chose to traverse the 3D matrix, the cells are numbered in their traversal order:

Conversion functions:

public int to1D( int x, int y, int z ) {
    return (z * xMax * yMax) + (y * xMax) + x;
}

public int[] to3D( int idx ) {
    final int z = idx / (xMax * yMax);
    idx -= (z * xMax * yMax);
    final int y = idx / xMax;
    final int x = idx % xMax;
    return new int[]{ x, y, z };
}

The code above could surely be factorised to be faster, but I left it as such to make it easier to understand the 2 way conversion ;)

๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 370375-index-a-3d-array-with-a-2d-array-of-indices
Index a 3D array with a 2D array of indices - MATLAB Answers - MATLAB Central
December 1, 2017 - I have a series of 3D arrays: A, B, C with same dimensions. Data is related between them in the sense that each cell corresponds to a different measurement at the same experiment conditions. With: ... M would be a 2D array with the maxima for each vector along the Z axis of the array A. idx would be de indexes along the Z axis vectors that correspond to those maxima.
Top answer
1 of 1
1

One approach -

def inside3d(input):
    # Get idx in 3D
    idx3d = np.floor(input).astype(np.int)

    # Create a similar mask as witrh 2D case, but in 3D now
    mask3d = grid[idx3d[:,:,0], idx3d[:,:,1]]==1

    # Count of mask matches for each index in 0th dim    
    counts = np.sum(mask3d,axis=1)

    # Index into input to get masked matches across all elements in 0th dim
    out_cat_array = input.reshape(-1,2)[mask3d.ravel()]

    # Split the rows based on the counts, as the final output
    return np.split(out_cat_array,counts.cumsum()[:-1])

Verify results -

Create 3D random input:

In [91]: random_pts3d = np.random.random(size=(3, 100, 2)) * len(grid)

With inside3d:

In [92]: inside3d(random_pts3d)
Out[92]: 
[array([[ 10.71196268,  12.9875877 ],
        [ 10.29700184,  10.00506662],
        [ 13.80111411,  14.80514828],
        [ 12.55070282,  14.63155383]]), array([[ 10.42636137,  12.45736944],
        [ 11.26682474,  13.01632751],
        [ 13.23550598,  10.99431284],
        [ 14.86871413,  14.19079225],
        [ 10.61103434,  14.95970597]]), array([[ 13.67395756,  10.17229061],
        [ 10.01518846,  14.95480515],
        [ 12.18167251,  12.62880968],
        [ 11.27861513,  14.45609646],
        [ 10.895685  ,  13.35214678],
        [ 13.42690335,  13.67224414]])]

With inside:

In [93]: inside(random_pts3d[0])
Out[93]: 
array([[ 10.71196268,  12.9875877 ],
       [ 10.29700184,  10.00506662],
       [ 13.80111411,  14.80514828],
       [ 12.55070282,  14.63155383]])

In [94]: inside(random_pts3d[1])
Out[94]: 
array([[ 10.42636137,  12.45736944],
       [ 11.26682474,  13.01632751],
       [ 13.23550598,  10.99431284],
       [ 14.86871413,  14.19079225],
       [ 10.61103434,  14.95970597]])

In [95]: inside(random_pts3d[2])
Out[95]: 
array([[ 13.67395756,  10.17229061],
       [ 10.01518846,  14.95480515],
       [ 12.18167251,  12.62880968],
       [ 11.27861513,  14.45609646],
       [ 10.895685  ,  13.35214678],
       [ 13.42690335,  13.67224414]])