Exercise 9.1: Matrix operations
Calculate A + A, AA>,A>A and AB. Write a function that computes A(B−λI) for any λ.
import numpy
def calc(A,B,x):
I=numpy.eye(m)
return numpy.dot(A,B-I*x)
n=200
m=500
A=numpy.random.normal(size=(n,m))
B=numpy.random.normal(size=(m,m))
for i in range(m):
for j in range(m):
if ((i
Exercise 9.2: Solving a linear system
Generate a vector b with m entries and solve Bx = b.
import numpy
n=200
m=500
A=numpy.random.normal(size=(n,m))
B=numpy.random.normal(size=(m,m))
for i in range(m):
for j in range(m):
if ((i
Exercise 9.3: Norms
Compute the Frobenius norm of A: kAkF and the infinity norm of B: kBk∞. Also find the largest and smallest singular values of B.
import numpy
import scipy
n=200
m=500
A=numpy.random.normal(size=(n,m))
B=numpy.random.normal(size=(m,m))
for i in range(m):
for j in range(m):
if ((i
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.
import numpy
import time
def infi_norm(x):
res=0
for i in range(n):
res=max(res,abs(x[i]))
return res
n=6
Z=numpy.random.normal(size=(n,n))
old=numpy.ones(n,dtype=float)
t0=time.clock()
r=1
new=numpy.dot(Z,old.T)
new=new/infi_norm(old)
while (infi_norm(old-new)>1e-6 and r<1e+6):
r=r+1
old=new
new=numpy.dot(Z,old.T)
new=new/infi_norm(old)
print(time.clock()-t0)
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?
import numpy
import scipy
n=5
p=0.3
A=numpy.random.rand(n,n)
C=numpy.where(A>p,0,1)
D=scipy.linalg.svdvals(C)
e=D.max()
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.
import numpy
import scipy
def find_nearest(A,z):
A=A-z
B=numpy.abs(A)
i=B.argmin()
return A.flatten()[i]+z