Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

matrix

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]])

like image 379
Anais Dawes Avatar asked Dec 08 '25 08:12

Anais Dawes


2 Answers

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.

like image 102
Prashant Neupane Avatar answered Dec 09 '25 20:12

Prashant Neupane


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))
like image 29
amitshree Avatar answered Dec 09 '25 21:12

amitshree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!