Skip to main content

MATH 345: Linear Algebra and Optimization

Section B.3 Indexing and Slicing

This section helps you read Python indexing and slicing as requests for entries, rows, columns, or blocks of a vector or matrix.
x = np.array([10, 20, 30, 40])

x[0]      # first entry
x[1]      # second entry
x[-1]     # last entry
x[:2]     # first two entries
x[2:]     # entries from index 2 onward
x[::-1]   # reversed order
A = np.array([[1, 2, 3],
              [4, 5, 6]])

A[0, 1]    # row 0, column 1
A[0, :]    # first row
A[:, 0]    # first column
A[:, 1]    # second column
A[:, :2]   # all rows, first two columns
The rank-\(k\) SVD reconstruction uses the same slicing language:
Ak = U[:, :k] @ np.diag(s[:k]) @ Vt[:k, :]

First entry.

Read as. The first entry of x.
Shape/return. A scalar.
Used for. Indexing.

Last entry.

x[-1]
Read as. The last entry of x.
Shape/return. A scalar.
Used for. Indexing.

Column extraction.

A[:, 0]
Read as. The first column of A.
Shape/return. A one-dimensional array.
Used for. Column extraction.

First columns.

A[:, :k]
Read as. All rows and the first k columns.
Shape/return. An array block.
Used for. SVD reconstruction.

First singular values.

s[:k]
Read as. The first k singular values.
Shape/return. A one-dimensional array.
Used for. SVD reconstruction.

First rows.

Vt[:k, :]
Read as. The first k rows and all columns.
Shape/return. An array block.
Used for. SVD reconstruction.

Reverse order.

[::-1]
Read as. Reverse the order.
Shape/return. A reordered array.
Used for. Rankings.
Boolean mask indexing selects entries where a Boolean array is true. In the optional attention notebook, S_masked[mask] = -1e9 changes only the entries where mask is true.