import numpy as np
n = 3
np.random.seed(22)
A = np.round(5*np.random.randn(n, n))
A[0,0] = 0
A
Now define a function row_swap_mat(i, j)
that returns a permutation matrix that swaps row i and j:
def row_swap_mat(i, j):
P = np.eye(n)
P[i] = 0
P[j] = 0
P[i, j] = 1
P[j, i] = 1
return P
What do these matrices look like?
row_swap_mat(0,1)
Do they work?
row_swap_mat(0,1).dot(A)
U
is the copy of A
that we'll modify:
U = A.copy()
Create P1 to swap up the right row:
P1 = row_swap_mat(0, 2)
U = P1.dot(U)
U
M1 = np.eye(n)
M1[1,0] = -U[1,0]/U[0,0]
M1
U = M1.dot(U)
U
Create P2
to swap up the right row:
P2 = row_swap_mat(1,2)
U = P2.dot(U)
U
M2 = np.eye(n)
M2[2,1] = -U[2,1]/U[1,1]
M2
U = M2.dot(U)
U
So we've built $M_2P_2M_1P_1A=U$.
M2.dot(P2).dot(M1).dot(P1).dot(A)
Can't simply sort the permutation matrices out of the way:
M2.dot(P2).dot(M1).dot(P1)
M2.dot(M1).dot(P2).dot(P1)
But: We now know the right reordering!
P = P2.dot(P1)
P
PA = P.dot(A)
PA