Indexing into a matrix is a means of selecting a subset of elements from the matrix. MATLAB has several indexing styles that are not only powerful and flexible, but also readable and expressive. Indexing is a key to MATLAB’s effectiveness at capturing matrix-oriented ideas in understandable computer programs.
Indexing is also closely related to another term MATLAB users often hear: vectorization. Vectorization means using MATLAB language constructs to eliminate program loops, usually resulting in programs that run faster and are more readable. Of the many possible vectorization techniques, many rely on MATLAB indexing methods, five of which are described in this article. To learn more about other similar methods, see the resources listed at the end of this article.
Let’s start with the simple case of a vector and a single subscript. The vector is
v = [16 5 9 4 2 11 7 14];
The subscript can be a single value.
v(3) % Extract the third element
Or the subscript can itself be another vector.
v([1 5 6]) % Extract the first, fifth, and sixth elements
16 2 11
MATLAB’s colon notation provides an easy way to extract a range of elements from v.
v(3:7) % Extract the third through the seventh elements
9 4 2 11 7
Swap the two halves of v to make a new vector.
v2 = v([5:8 1:4]) % Extract and swap the halves of v
2 11 7 14 16 5 9 4
The special end operator is an easy short-hand way to refer to the last element of v.
v(end) % Extract the last element
The end operator can be used in a range.
v(5:end) % Extract the fifth through the last elements ans =
2 11 7 14
You can even do arithmetic using end.
v(2:end-1) % Extract the second through the next-to-last elements
5 9 4 2 11 7
Combine the colon operator and end to achieve a variety of effects, such as extracting every k-th element or flipping the entire vector.
v(1:2:end) % Extract all the odd elements
16 9 2 7
v(end:-1:1) % Reverse the order of elements
14 7 11 2 4 9 5 16
By using an indexing expression on the left side of the equal sign, you can replace certain elements of the vector.
v([2 3 4]) = [10 15 20] % Replace some elements of v
16 10 15 20 2 11 7 14
Usually the number of elements on the right must be the same as the number of elements referred to by the indexing expression on the left. You can always, however, use a scalar on the right side.
v([2 3]) = 30 % Replace second and third elements by 30
16 30 30 20 2 11 7 1 4
This form of indexed assignment is called scalar expansion.