|Programming and Data Types|
Creating Multidimensional Arrays
You can use the same techniques to create multidimensional arrays that you use for two-dimensional matrices. In addition, MATLAB provides a special concatenation function that is useful for building multidimensional arrays.
This section discusses:
catfunction to build multidimensional arrays
Generating Arrays Using Indexing
One way to create a multidimensional array is to create a two-dimensional array and extend it. For example, begin with a simple two-dimensional array
A is a 3-by-3 array, that is, its row dimension is 3 and its column dimension is 3. To add a third dimension to
MATLAB responds with
You can continue to add rows, columns, or pages to the array using similar assignment statements.
Extending Multidimensional Arrays. To extend
A in any dimension:
You can take advantage of the MATLAB scalar expansion capabilities, together with the colon operator, to fill an entire dimension with a single value.
A into a 3-by-3-by-3-by-2, four-dimensional array, enter
Note that after the first two assignments MATLAB pads
A with zeros, as needed, to maintain the corresponding sizes of dimensions.
Generating Arrays Using MATLAB Functions
You can use MATLAB functions
generate multidimensional arrays in the same way you use them for two-dimensional arrays. Each argument you supply represents the size of the corresponding dimension in the resulting array. For example, to create a 4-by-3-by-2 array of normally distributed random numbers.
To generate an array filled with a single constant value, use the
repmat replicates an array (in this case, a 1-by-1 array) through a vector of array dimensions.
Any dimension of an array can have size zero, making it a form of empty array. For example, |
Building Multidimensional Arrays with the cat Function
cat function is a simple way to build multidimensional arrays; it concatenates a list of arrays along a specified dimension.
A2, and so on are the arrays to concatenate, and
dim is the dimension along which to concatenate the arrays. For example, to create a new array with
cat function accepts any combination of existing and new data. In addition, you can nest calls to
cat. The lines below, for example, create a four-dimensional array.
cat automatically adds subscripts of 1 between dimensions, if necessary. For example, to create a 2-by-2-by-1-by-2 array, enter
In the previous case,
cat inserts as many singleton dimensions as needed to create a four-dimensional array whose last dimension is not a singleton dimension. If the
dim argument had been
5, the previous statement would have produced a 2-by-2-by-1-by-1-by-2 array. This adds additional
1s to indexing expressions for the array. To access the value
8 in the four-dimensional case, use
|Multidimensional Arrays||Accessing Multidimensional Array Properties|