The function calculates the RREF and null space of a given matrix with the exception of one case; where the matrix is already in RREF.
def r_r_e_f(matrix):
a=matrix.copy()
m, n=numpy.shape(a)
i=0
j=0
rank=0
l=[]
while i<=(m-1) and j<=(n-1):
p=numpy.max(numpy.abs(a[i:m, j]))
max_p=numpy.argmax(numpy.abs(a[i:m, j]))
k=max_p+i
if p==0 or p<=0.0000000000000000001:
j=j+1
else:
rank=rank+1
c=a.copy()
c[k, :]=a[i, :]
c[i, :]=a[k, :]
a=c.copy()
a[i, :]=a[i, :]/a[i, j]
l.append(j)
for x in range(0, m):
if x!=i:
a[x, :]=a[x, :]-a[x, j]*a[i, :]
i=i+1
j=j+1
ncols=[]
for col in range(n):
if col not in l:
ncols.append(col)
nbasis=[]
for col in ncols:
basis=numpy.zeros(n)
basis[col]=1
for row in range(len(l)):
pcol=l[row]
basis[pcol]=-a[row, col]
nbasis.append(basis)
return a, nbasis
matrix=numpy.array([[1,0,3,0],[0,0,2,1]], dtype=float)
rref, null_space=r_r_e_f(matrix)
print(matrix)
print("RREF of the matrix: ")
print(rref)
print("basis of null space of the matrix: ")
formatm=[]
if null_space==[]:
print("null space is a 0 vector")
else:
for bv in null_space:
reformat=bv.reshape(-1, 1)
formatm.append(reformat)
for i in formatm:
print(i)
When the matrix provided is already in RREF, the program does not return the correct basis of null space. Can someone please help me identify the problem.`
Here is the output for a matrix that is already in RREF
Matrix:
[[1. 0. 3. 0.]
[0. 0. 2. 1.]]
RREF of the matrix:
[[1. 0. 3. 0.]
[0. 0. 2. 1.]]
basis of null space of the matrix:
[[-0.]
[ 1.]
[ 0.]
[ 0.]]
[[-3.]
[ 0.]
[ 1.]
[ 0.]]
[[-0.]
[ 0.]
[ 0.]
[ 1.]]
The correct output should return the vectors: [0, 1, 0. 0] and [1.5, 0, -0.5, 1]
However for a matrix which is not in RREF, the output is as expected: Matrix: [[1,2,3,0],[0,2,2,1]] basis of null space of the matrix:
[[-1.]
[-1.]
[ 1.]
[ 0.]]
[[ 1. ]
[-0.5]
[ 0. ]
[ 1. ]]