Exercise 8.2: Working with two-dimensional arrays¶
[1]:
import numpy as np
Numpy enables you do to matrix calculations on two-dimensional arrays. In exercise, you will practice doing matrix calculations on arrays. We’ll start by making a matrix and a vector to practice with. You can copy and paste the code below.
[2]:
A = np.array(
[
[6.7, 1.3, 0.6, 0.7],
[0.1, 5.5, 0.4, 2.4],
[1.1, 0.8, 4.5, 1.7],
[0.0, 1.5, 3.4, 7.5],
]
)
b = np.array([1.1, 2.3, 3.3, 3.9])
a) First, let’s practice slicing.
Print row 1 (remember, indexing starts at zero) of
A.Print columns 1 and 3 of
A.Print the values of every entry in
Athat is greater than 2.Print the diagonal of
A. using thenp.diag()function.
b) The np.linalg module has some powerful linear algebra tools.
First, we’ll solve the linear system \(\mathsf{A}\cdot \mathbf{x} = \mathbf{b}\). Try it out: use
np.linalg.solve(). Store your answer in the Numpy arrayx.Now do
np.dot(A, x)to verify that \(\mathsf{A}\cdot \mathbf{x} = \mathbf{b}\).Use
np.transpose()to compute the transpose ofA.Use
np.linalg.inv()to compute the inverse ofA.
c) Sometimes you want to convert a two-dimensional array to a one-dimensional array. This can be done with np.ravel().
See what happens when you do
B = np.ravel(A).Look of the documentation for
np.reshape(). Then, reshapeBto make it look likeAagain.