In this task you are practicing using NumPy in several applications.
Write a function that would take in a matrix and a non-negative integer, check for that matrix is square, and return the power of the matrix computed through successive multiplication.
import numpy as np
def matrix_power(mtrx,n=1):
# Write your code here
pass
A = np.array([[1,2,0],[0,2,3],[1,1,5]])
print(matrix_power(A))
Here are the tests to pass for your code (which are referred to as unit tests)
# Test the code above
A = np.array([[1,2,0],[0,2,3],[1,1,5]])
B = [[355,614,1806],[903,1565,4533],[1210,2113,6098]]
eq=np.equal(matrix_power(A,5),B)
if eq.all():
print('Test 1 passed')
else:
print('Test 1 FAIL')
A = [[1,2,0],[0,2,3],[1,1,5]]
B = [[355,614,1806],[903,1565,4533],[1210,2113,6098]]
eq=np.equal(matrix_power(A,5),B)
if eq.all():
print('Test 2 passed')
else:
print('Test 2 FAIL')
try:
matrix_power([1],4.5)
except TypeError:
print('Test 3 passed')
except:
print('Test 3 FAIL')
else:
print('Test 3 FAIL')
try:
matrix_power([1],-5)
except ValueError:
print('Test 4 passed')
except:
print('Test 4 FAIL')
else:
print('Test 4 FAIL')
Consider the AR(1) model
$$ y_t = a y_{t-1} + \varepsilon, \; \varepsilon \sim N(0, 1). $$We can represent it in the form
$$ Ay = \varepsilon \quad \quad \varepsilon \sim N(0, 1) $$where $ A $ is
$$ A = \begin{bmatrix} 1 & 0 & \cdots & 0 & 0 \cr -a & 1 & \cdots & 0 & 0 \cr \vdots & \vdots & \cdots & \vdots & \vdots \cr \vdots & \vdots & \cdots & 1 & 0 \cr 0 & 0 & \cdots & -a & 1 \end{bmatrix} $$and $ y $ and $ \varepsilon $ are $ (T x 1) $ vectors
Generate an AR(1) series with $ T=500 $ and $ \alpha = 0.9 $ using matrix algebra, and make a plot of $ y_t $.
Hint: use NumPy.eye() with additional arguments.
# replace @@@ by your code
import numpy as np
T = @@@
α = @@@
ɛ = np.random.randn(T)
A = @@@
y = @@@
import matplotlib.pyplot as plt
@@@