# 1.2 Multi-dimensional Arrays in MATLAB

Can you use multi-dimensional arrays in MATLAB? There is no direct way to access more than two dimensions in MATLAB v4.x.

It is possible, however, to create your own functions in MATLAB to handle multi-dimensional arrays. The following is an example that maps a three-dimensional array to a single vector. The indices are passed to a function as if it is a 3-D array and they are then translated to a single vector with corresponding offsets. The exact implementation will be specific to what you want to accomplish.

```function position = index3(d,i,j,k)
% INDEX3   POSITION = INDEX3(d,i,j,k) indexes a 3-D array
% i,j, and k are the indices of interest.
% d is a 3-element vector that specifies the dimensions
% of the array.
% This function only works when your dimensions are equal.
% e.g. a 3x3x3.
position = (i+(j-1)*d(2)+(k-1)*d(2)*d(3));
```
The following is an example of how you might use this function.

```D = [3 3 3];               % D defines the dimensions as
% 3x3x3
A1 = [ 1  2  3;
4  5  6;
7  8  9];           % Set up the three arrays to
% stack
A2 = [10 11 12;
13 14 15;
16 17 18];
A3 = [19 20 21;
22 23 24;
25 26 27];
A3D = [A1 A2 A3];          % A3D is where your 3-D data is
% stored
B1 = A3D(index3(D,1,3,2)); % 1st row, 3rd column, 2nd
% matrix
A3D(index3(D,1,3,2)) = 77; % Write to it
B2 = A3D(index3(D,1,3,2)); % Read from it
```
It is possible to create N-dimensional arrays with different limits on each dimension. The main difference is that the offset will change so that it correctly indexes through your matrix. Each additional dimension will require a corresponding offset. You can add error checking for the indices to make sure you do not go out of bounds.

You can also emulate 3-D arrays by packing them into 2-D arrays with the meshgrid function. For example, given three arguments

```[X,Y,Z] = meshgrid(x,y,z)
```
grids and packs the data into matrices like

```X = [X1(:) X2(:) X3(:) ...]
```
where each Xi(:) is the gridded matrix for a fixed value of Z (a similar packed matrix is used for Y and Z). That is, a m-by-n-by-p array is packed into a (m*n)-by-p matrix.

The routine slice uses this packed format to display a "slice" through the data. The M-files for meshgrid and slice are short so if you study these you should be able to understand what is going on. Since MATLAB only knows about the row and column dimensions you have to have an additional piece of information to determine the size of the 3-D array (slice uses the number of rows).

We also do some 3-D packing for the image deck format in the Image Processing Toolbox. If you have that toolbox, look at the routines imslice and montage.

(c) Copyright 1994 by The MathWorks, Inc.