Indexing
Indexing is used to retrieve one or more specific values out of a collection.
The () characters are used to indicate indexing of a variable. The value(s) between the
()’s are the indices.
a=[1,2,3;4,5,6]
b=a(1,2)
This retrieves the
value from the first row, second column of the matrix referred to by variable
a and assigns it to variable b.Indices must be positive integers. The first element is always 1.
Indexing can also be used to assign values to a specific location in a
collection:
a(2,3)=-3
For vectors, only a single index needs to be
specified.x=[1,2,3]
x(2)
A single index may also be used when indexing into a matrix. This is interpreted as the nth
element, starting at the 1,1 position and counting down columns first, and then across
rows.
a=[1,2,3;4,5,6]
a(2)
a(5)
In the above example
a(2) refers to 4 and a(5) refers to 3.When extracting a value, if an index exceeds the size of a collection, an error
occurs.
A=[1,2,3]
A(4) – causes an error
However, if an index exceeds
the size of a collection during an assignment, the collection is automatically resized to
accommodate the new element. Any intermediate elements are initialized to
0.A=[1,2,3]
A(5)=9
Matrix A now has 5 elements – [1,2,3,0,9].The : can be used to request an entire row or column when indexing.
A=[1,2,3;4,5,6]
A(1,:)=> [1,2,3] (returns the first row)
A(:,1)=> [1;4] (returns the first column)
A vector or matrix can also be indexed by range.
A = [1 8 3 2 0 4]
A(2:5) => [8 3 2 0]
When indexing a collection, the end function can be used to return the
index of the last element of the
collection.
A(2:end) => [8 3 2 0 4]
Rows and columns of a matrix can be removed by assigning them to an empty
matrix.
A=[1,2,3;4,5,6]
A(1,:) = []
A => [4,5,6]
The same applies to
assigning a subsection of a matrix to a new
value:A=[1,2,3;4,5,6]
A(1,:) = 0
A => [0,0,0;4,5,6]
Indices must normally be positive integers. However, when using a special type of variable
known as a logical variable, they can be 0 or 1. When a logical index is 0, the
corresponding element is not included in the result. When a logical index is 1, it is
included.
A=[1,2,3,4]
A(logical([0,1,1,0])) => [2,3]
The size of the
logical matrix must match the size of the matrix being indexed.