Numpy exercises
Generate matrices A, with random Gaussian entries, B, a Toeplitz matrix, where A ∈R^(n×m) and B ∈R^(m×m), for n = 200, m = 500.
Exercise 9.1: Matrix operations Calculate A + A, AA,AAT and AB. Write a function that computes A(B−λI) for any λ.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import numpy as np
from scipy.linalg import toeplitz
A = np.random.normal(0.,1.,(200,500))
B = toeplitz(np.array(list(range(1,501))))
sumA = A+A
productA = A.dot(A.T)
productAT = A.T.dot(A)
productAB = A.dot(B)
print("sum A+A:")
print(sumA)
print("product AA:")
print(productA)
print('product AAT:')
print(productAT)
print('product AB:')
print(productAB)
def compute(A,B,linda):
temp = B-linda*np.eye(500)
return A@BExercise 9.2: Solving a linear system Generate a vector b with m entries and solve Bx = b.
1 |
|
- Exercise 9.3: Norms Compute the Frobenius norm of A: |A|F and the infinity norm of B: |B|∞. Also find the largest and smallest singular values of B.
1 | form numpy import linalg as LA |
- Exercise 9.4: Power iteration Generate a matrix Z, n × n, with Gaussian entries, and use the power iteration to find the largest eigenvalue and corresponding eigenvector of Z. How many iterations are needed till convergence? Optional: use the time.clock() method to compare computation time when varying n.
1 | import time |
- Exercise 9.5: Singular values Generate an n×n matrix, denoted by C, where each entry is 1 with probability p and 0 otherwise. Use the linear algebra library of Scipy to compute the singular values of C. What can you say about the relationship between n, p and the largest singular value?
1 | n=200 |
- Exercise 9.6: Nearest neighbor Write a function that takes a value z and an array A and finds the element in A that is closest to z. The function should return the closest value, not index. Hint: Use the built-in functionality of Numpy rather than writing code to find this value manually. In particular, use brackets and argmin.
1 | def NearNb(A,z): |