Indexing
Indexing is used to retrieve one or more specific values out of a collection.
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.
a(2,3)=-3
For vectors, only a single index needs to be
specified.x=[1,2,3]
x(2)
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.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].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 = [1 8 3 2 0 4]
A(2:5) => [8 3 2 0]
A(2:end) => [8 3 2 0 4]
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]
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.