Multidimensional Arrays



Prev TutorialNext Tutorial

An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix.
Generally to generate a multidimensional array, we first create a two-dimensional array and extend it.
For example, let's create a two-dimensional array a.

a = [7 9 5; 6 1 9; 4 3 2]
MATLAB will execute the above statement and return the following result −
a =
     7     9     5
     6     1     9
     4     3     2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −

a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
a(:,:,1) =
     7     9     5
     6     1     9
     4     3     2

a(:,:,2) =
     1     2     3
     4     5     6
     7     8     9
We can also create multidimensional arrays using the ones(), zeros() or the rand() functions.
For example,

b = rand(4,3,2)
MATLAB will execute the above statement and return the following result −
b(:,:,1) =
    0.0344    0.7952    0.6463
    0.4387    0.1869    0.7094
    0.3816    0.4898    0.7547
    0.7655    0.4456    0.2760

b(:,:,2) =
    0.6797    0.4984    0.2238
    0.6551    0.9597    0.7513
    0.1626    0.3404    0.2551
    0.1190    0.5853    0.5060
We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension −
Syntax for the cat() function is −
B = cat(dim, A1, A2...)
Where,
  • B is the new array created
  • A1A2, ... are the arrays to be concatenated
  • dim is the dimension along which to concatenate the arrays

Example

Create a script file and type the following code into it −
a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
When you run the file, it displays −
c(:,:,1) =
     9     8     7
     6     5     4
     3     2     1
c(:,:,2) =
     1     2     3
     4     5     6
     7     8     9
c(:,:,3) =
     2     3     1
     4     7     8
     3     9     0

Prev TutorialNext Tutorial