# Multidimensional Matrices

OML supports multidimensional matrices.

This is an extension of the 2D matrices (see Collections), where data can be added and extracted across multiple dimensions.

There is no limit to the number of dimensions, apart from the maximum 32-bit integer size
and the machine memory required to store the
matrix.

```
b = ones(2); ==> b is a 2x2 matrix
b(:,:,3) = [5,6;7,8] ==> b is now a 2x2x3 matrix as follows:
slice(:, :, 1) =
[Matrix] 2 x 2
1 1
1 1
slice(:, :, 2) =
[Matrix] 2 x 2
0 0
0 0
slice(:, :, 3) =
[Matrix] 2 x 2
5 6
7 8
```

All rules that apply to accessing elements of a 2D matrix also apply to multidimensional matrices.

For example, running this
script:

```
m3m = ones(2,2);
m3m(:,:,2) = [5,6;7,8];
m3m(:)
m3m(:,:,:)
m3m(1)
m3m(:,1,:)
m3m(1,:,2)
```

produces this
output:

```
ans = [Matrix] 8 x 1
1
1
1
1
5
7
6
8
ans =
slice(:, :, 1) =
[Matrix] 2 x 2
1 1
1 1
slice(:, :, 2) =
[Matrix] 2 x 2
5 6
7 8
ans = 1
ans =
slice(:, :, 1) =
[Matrix] 2 x 1
1
1
slice(:, :, 2) =
[Matrix] 2 x 1
5
7
ans = [Matrix] 1 x 2
5 6
```

The colon operator provides considerable flexibility in how data can be assigned to a
matrix. Consider this example:

`m(2,:,:) = [1,2;3,4]`

The left-hand side
is expecting to assign data in dimensions 2 and 3, but the right-hand side has data in
dimensions 1 and 2. Strictly, this might be regarded as an error. However, it is useful to
allow an implicit assignment of the two right-hand side dimensions to the two colon
dimensions on the left to produce the following
result:```
m =
slice(:, :, 1) =
[Matrix] 2 x 2
0 0
1 3
slice(:, :, 2) =
[Matrix] 2 x 2
0 0
2 4
```

By
allowing both `m(:,:,2)`

and `m(2,:,:)`

on the left-hand side,
you can interpret the dimensions of `m`

as either (row, col, page) or (page,
row, col). This kind of flexibility applies to all numbers of dimensions and colons.Similarly, to 2D matrices, setting one value of an element defines the size. For
example:

```
m3m(2,2,2) = 1
m3m =
slice(:, :, 1) =
[Matrix] 2 x 2
0 0
0 0
slice(:, :, 2) =
[Matrix] 2 x 2
0 0
0 1
```

Many functions do not operate on multidimensional matrices (for example, matrix inversion).
However, it can often be useful to extract data two dimensions at a time and reformat them
into a two-dimensional matrix using the squeeze or
reshape functions. Consider this sequence that creates a
two-dimensional matrix b from dimensions 1 and 3 of
m.

```
m(2,:,:) = [1,2;3,4];
b = m(:,1,:) ==> here b is a 2x1x2 matrix
b = squeeze(b) ==> here b is now a 2x2 matrix
```

A matrix can also be reduced to a 2D matrix by deleting higher dimensions. For
example:

```
b = ones(2,2)
b(:,:,2) = [5,6;7,8]; ==> here b is a 2x2x2 matrix
b(:,:,2) = []; ==> here b is now a 2x2 matrix
```