Anais Dawes
Anais Dawes

Reputation: 33

How do I reduce a matrix to row echelon form using numpy?

I am trying to get any square matrix A (nxn) that is augmented with a (3x1) matrix and reduce it to row echelon. I tried some things but they don't seem to work quite right and I can't figure it out.

def first_column_zeros(A):

B=np.copy(A)
for i in range(1,len(B)):

    B[i]=B[i]-(B[i,0]/B[0,0])*(B[0])

return B

def row_echelon(A,b):

Ab=np.column_stack((A,b))
C=np.copy(Ab)
first_column_zeros(Ab)

for i in range(1,len(C)):
    C[i]=(C[i])-((C[i,i-1])/(C[i-1,i-1]))*c[0]

return C

When, A=np.array([[2,1,3,1],[1,2,-1,2.5],[4,2,-1,1]]) first_column_zeros(A)

is executed, the output should be array(([3., 1., -2., 1.1], [0., 1.666666667, -4.33333333, 1.633333333, [0., 0., -9.8, 0.84]])

Upvotes: 2

Views: 16008

Answers (3)

Physicing
Physicing

Reputation: 542

I'm sure that numpy does not have that. Check here.

However, I suggest you to check scipy, sympy.

Furthermore, you can also check here for more similar problems that people experienced before. This problem has solved by numpy but with creating it manually.

Upvotes: 1

amitshree
amitshree

Reputation: 2298

Numpy doesn't have a method to get row echelon form (REF) or reduced row echelon form (RREF) of a matrix.

To get REF and RREF you can use sympy library.

Code example:

import numpy as np
from sympy import Matrix

m = 4
n = 3

# Creat a numpy matrix

npMatrix = np.random.randn(m, n);

# Convert to sympy matrix
A = Matrix(npMatrix)

# Get REF
REF = A.echelon_form()

print(np.array(REF))

# Get RREF
RREF = A.rref()[0]

print(np.array(RREF))

Upvotes: 1

Prashant Neupane
Prashant Neupane

Reputation: 31

You can use sympy library which has a method rref()

from sympy import *
m = Matrix([
        [.85, -.15, -.7, 0, 0],
        [-.15, .8, -.4, -.25, 0],
        [-.1, -.1, .45, -.25, 0],
        [-.25, -.1, -.4, .75, 0]])
M_rref = m.rref()
print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref))

You might have to install sympy package if you do not have it previously.

Upvotes: 3

Related Questions