Skip to main content
Contents
Dark Mode Prev Up Next
\(\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\dimens}{\operatorname{dim}}
\DeclareMathOperator{\row}{\operatorname{row}}
\DeclareMathOperator{\col}{\operatorname{col}}
\newcommand{\im}{\operatorname{im}}
\newcommand{\nulls}{\operatorname{null}}
\newcommand{\minor}{\operatorname{minor}}
\newcommand{\spans}{\operatorname{span}}
\newcommand{\nullity}{\operatorname{nullity}}
\newcommand{\kers}{\operatorname{ker}}
\newcommand{\proj}{\operatorname{proj}}
\newcommand{\diag}{\operatorname{diag}}
\newcommand{\Tr}{\operatorname{Tr}}
\newcommand{\rank}{\operatorname{rank}}
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
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.
Last entry.
Read as. The last entry of
x.
Column extraction.
Read as. The first column of
A.
Shape/return. A one-dimensional array.
Used for. Column extraction.
First columns.
Read as. All rows and the first
k columns.
Shape/return. An array block.
Used for. SVD reconstruction.
First singular values.
Read as. The first
k singular values.
Shape/return. A one-dimensional array.
Used for. SVD reconstruction.
First rows.
Read as. The first
k rows and all columns.
Shape/return. An array block.
Used for. SVD reconstruction.
Reverse order.
Read as. Reverse the order.
Shape/return. A reordered array.
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.
Activity B.3.1 . Check Yourself: Slices.
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
What is the shape of each result?