from sympy import *
from IPython.display import display
init_printing(use_latex='mathjax')
height = lambda M: len(M[:,0])
width = lambda M: len(M[0,:])
A=Matrix([[1,3,5,0,0,3],[0,0,2,1,2,1],[2,6,12,1,2,7]])
display(A)
Ar,pivots=A.rref()
display(Ar,pivots)
#The echolon rows form a basis of the
#row space of the orginal matrix A.
display(Ar[0:len(pivots),:].transpose())
#The columns of A that become pivots
#form a basis of column space of A.
CB=zeros(len(A[:,0]),len(pivots))
for j in range(len(pivots)):
CB[:,j]=A[:,pivots[j]]
display(CB)
def kernel_basis(A):
'''Returns matrix whose column are a basis for the null space of A.'''
#1. n x n matrix identity matrix B.
#2. m x n matrix R = rref of A.
#3. Subtract each row i of R from row i of B.
#4. For each pivot column j of R, delete column j of B.
m=width(A)
B=eye(m)
tmp=Matrix(A)
R,pivots=tmp.rref()
cols=range(m)
for (p,e) in zip(pivots,range(len(pivots))):
for c in cols:
B[p,c]=B[p,c]-R[e,c]
for p in reversed(pivots):
B.col_del(p)
return(B)
#The free columns of the RREF of A
#encode a basis of the kernel of A.
kernel_basis(A)