Programming and Data Types    

Advanced Indexing

MATLAB stores each array as a column of values regardless of the actual dimensions. This column consists of the array columns, appended end to end.

For example, MATLAB stores

as

Accessing A with a single subscript indexes directly into the storage column. A(3) accesses the third value in the column, the number 3. A(7) accesses the seventh value, 9, and so on.

If you supply more subscripts, MATLAB calculates an index into the storage column based on the dimensions you assigned to the array. For example, assume a two-dimensional array like A has size [d1 d2], where d1 is the number of rows in the array and d2 is the number of columns. If you supply two subscripts (i,j) representing row-column indices, the offset is

Given the expression A(3,2), MATLAB calculates the offset into A's storage column as (2-1)*3+3, or 6. Counting down six elements in the column accesses the value 0.

Indexing Into Multidimensional Arrays

This storage and indexing scheme also extends to multidimensional arrays. In this case, MATLAB operates on a page-by-page basis to create the storage column, again appending elements columnwise.

For example, consider a 5-by-4-by-3-by-2 array C.

Again, a single subscript indexes directly into this column. For example, C(4) produces the result

If you specify two subscripts (i,j) indicating row-column indices, MATLAB calculates the offset as described above. Two subscripts always access the first page of a multidimensional array, provided they are within the range of the original array dimensions.

If more than one subscript is present, all subscripts must conform to the original array dimensions. For example, C(6,2) is invalid, because all pages of C have only five rows.

If you specify more than two subscripts, MATLAB extends its indexing scheme accordingly. For example, consider four subscripts (i,j,k,l) into a four-dimensional array with size [d1 d2 d3 d4]. MATLAB calculates the offset into the storage column by

For example, if you index the array C using subscripts (3,4,2,1), MATLAB returns the value 5 (index 38 in the storage column).

In general, the offset formula for an array with dimensions [d1 d2 d3 ... dn] using any subscripts (s1 s2 s3 ... sn) is

Because of this scheme, you can index an array using any number of subscripts. You can append any number of 1s to the subscript list because these terms become zero. For example,

is equivalent to


  Subscripting and Indexing Empty Matrices