Section 1.5 Accessing the entries of vectors and matrices
We often need to manipulate matrices and vectors by extracting, replacing or rearranging some elements. The elements are indexed starting with 1: so, after executing v = [8 6 -4]
we find that v(1)
is 8, v(2)
is 6, and v(3)
is -4. One can also use indexing from the end of the vector: v(end)
is -4, v(end-1)
is 6, and so on. For a matrix the indexes are ordered as (row, column). So, if A = [5 6 7; 9 8 6]
, then A(1, 3)
is 7 and A(2, 1)
is 9.
A powerful tool for working with matrices is the colon : selector. When it replaces an index, it means “run through all values of that index”. Given a matrix A, we can use A(1, :)
to get its first row, A(:, 2)
to get the second column, and A(:, end)
for the last column.
We can use a vector of indexes to extract several elements of a vector or a matrix. For example, v(3:end-1)
extracts all entries of v
starting with the 3rd one and ending with the one before the last. If v
was [8 6 4 3 2 1]
, the result would be [4 3 2]
. For another example, v(2:2:end)
extracts all even-numbered elements of v. In the above example this would be [6 3 1]
. For a matrix A
, we can select both rows and columns at the same time: A(2:3, 2:5)
means taking the elements of A
that appear in rows 2-3 and in columns 2-5. The result is a submatrix of size 2×4.
The entries can also be assigned, for example v(2:2:end) = -3
makes all even-numbered entries of vector v
equal to -3.
Example 1.5.1. Extracting submatrices.
Display the 2×2 submatrix in the middle of a given 4×4 matrix such as
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]; B = A(2:3, 2:3); disp(B)