Exercise 3.8: 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
A
that 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, reshapeB
to make it look likeA
again.
Solution
a)
[3]:
# 1.
print('first row of A:\n', A[1,:])
# 2.
print('\ncolumns 1 and 3 of A:\n', A[:,[1,3]])
# 3.
print('\nvalues of every entry in A that is greater than 2:\n', A[A>2])
# 4.
print('\ndiagonal of A:\n', np.diag(A))
first row of A:
[0.1 5.5 0.4 2.4]
columns 1 and 3 of A:
[[1.3 0.7]
[5.5 2.4]
[0.8 1.7]
[1.5 7.5]]
values of every entry in A that is greater than 2:
[6.7 5.5 2.4 4.5 3.4 7.5]
diagonal of A:
[6.7 5.5 4.5 7.5]
b)
[4]:
# 1.
x = np.linalg.solve(A, b)
# 2.
print('A . x:\n', np.dot(A, x))
print('\nb:\n', b)
# 3.
print('\ntranspose of A:\n', np.transpose(A))
# 4.
print('\ninverse of A:\n', np.linalg.inv(A))
A . x:
[1.1 2.3 3.3 3.9]
b:
[1.1 2.3 3.3 3.9]
transpose of A:
[[6.7 0.1 1.1 0. ]
[1.3 5.5 0.8 1.5]
[0.6 0.4 4.5 3.4]
[0.7 2.4 1.7 7.5]]
inverse of A:
[[ 0.15267508 -0.03365026 -0.01778 0.00054854]
[-0.00906001 0.19788853 0.03719385 -0.07090934]
[-0.04391535 -0.0144834 0.26880108 -0.05219479]
[ 0.02172029 -0.0330119 -0.12929526 0.17117684]]
c)
[5]:
# 1.
B = np.ravel(A)
print('result of np.ravel(A):\n', B)
# 2.
A_from_reshape = np.reshape(B, A.shape)
print('\nA from reshaped B:\n', A_from_reshape)
result of np.ravel(A):
[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. 1.5 3.4 7.5]
A from reshaped B:
[[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. 1.5 3.4 7.5]]
Computing environment
[6]:
%load_ext watermark
%watermark -v -p numpy,jupyterlab
Python implementation: CPython
Python version : 3.9.12
IPython version : 8.3.0
numpy : 1.21.5
jupyterlab: 3.3.2