Open In App

Converting Matrix into Row Echelon Form in Python

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how we can convert the matrix into a Row Echelon Form. We will see how we can do this with the help of a Python Program for converting the matrix to Row Echelon Form.

What is the Row Echelon Form?

A matrix is in Row Echelon form if it has the following properties:

  • Any row consisting entirely of zeros occurs at the bottom of the matrix.
  • For each row that does not contain entirely zeros, the first non-zero entry is 1 (called a leading 1)
  • For two successive (non-zero) rows, the leading 1 in the higher row is further left than the leading one in the lower row.

Any matrix can be transformed into a row echelon and reduced row echelon form, using a technique called Gaussian elimination. This is particularly useful for solving systems of linear equations.

Gaussian Elimination

Gaussian Elimination is a way of converting a matrix into the row echelon and reduced row echelon form. It can also be used as a way of finding a solution to a solution to the system of linear equations. The idea behind this is that we perform some mathematical operations on the row and continue until only one variable is left.

Below are some operations that we can perform:

  • Interchange any two rows
  • Add two rows together.
  • Multiply one row by a non-zero constant (i.e. 1/3, -1/5, 2).

Reduce a Matrix to Row Echelon Form

Below are the steps by which we can convert the matrix into Row Echelon Form in Python:

Step 1: Check for Non-Zero Rows

Traverse through first column of the matrix to search for non-zero entries. Below is the function in which we are checking for non-zero rows.

Python3




def find_nonzero_row(matrix, pivot_row, col):
    nrows = matrix.shape[0]
    for row in range(pivot_row, nrows):
        if matrix[row, col] != 0:
            return row
    return None


Step 2: Swap Rows

After finding a non-zero entry, bring non-zero row to the top of the matrix so that we can achieve our first step towards row echelon form(by swapping rows). Below is the code part that we will use in our main code for swapping the rows. In this case, our non-zero row is the first row so it will be swapped by itself

Python3




def swap_rows(matrix, row1, row2):
    matrix[[row1, row2]] = matrix[[row2, row1]]


Step 3: Make Pivot Element of Pivot Row “1”

It is not compulsory to make the pivot element(First non-zero entry from the left) 1 but we will make it 1 for convenience. This is done by floor dividing the pivot row(In this case, first row) by pivot element(which is 2). After dividing row will become [2//2=1 , 3//2=1]

Python3




def make_pivot_one(matrix, pivot_row, col):
    pivot_element = matrix[pivot_row, col]
    matrix[pivot_row] //= pivot_element


Step 4: Eliminate Elements Below Pivots to get Row Echelon Form

Last step is to eliminate all the entries below the pivot element(making them zero). This is done by multiplying the element below pivot element with pivot row(which is in this case, first row) and then subtracting it from second row

Python3




def eliminate_below(matrix, pivot_row, col):
    nrows = matrix.shape[0]
    pivot_element = matrix[pivot_row, col]
    for row in range(pivot_row + 1, nrows):
        factor = matrix[row, col]
        matrix[row] -= factor * matrix[pivot_row]


Step 5: Implement All Functions Above

In this step, we are implementing all functions that we have declared above.

Python3




def row_echelon_form(matrix):
    nrows = matrix.shape[0]
    ncols = matrix.shape[1]
    pivot_row = 0
# this will run for number of column times. If matrix has 3 columns this loop will run for 3 times
    for col in range(ncols):
        nonzero_row = find_nonzero_row(matrix, pivot_row, col)
        if nonzero_row is not None:
            swap_rows(matrix, pivot_row, nonzero_row)
            make_pivot_one(matrix, pivot_row, col)
            eliminate_below(matrix, pivot_row, col)
            pivot_row += 1
    return matrix


Full Code Implementation

Below is the full Python code implementation to convert matrix into Row Echelon Form.

Python3




import numpy as np
# Function to check if matrix is in REF
  
def is_row_echelon_form(matrix):
    if not matrix.any():
        return False
  
    rows = matrix.shape[0]
    cols = matrix.shape[1]
    prev_leading_col = -1
  
    for row in range(rows):
        leading_col_found = False
        for col in range(cols):
            if matrix[row, col] != 0:
                if col <= prev_leading_col:
                    return False
                prev_leading_col = col
                leading_col_found = True
                break
        if not leading_col_found and any(matrix[row, col] != 0 for col in range(cols)):
            return False
    return True
  
def find_nonzero_row(matrix, pivot_row, col):
    nrows = matrix.shape[0]
    for row in range(pivot_row, nrows):
        if matrix[row, col] != 0:
            return row
    return None
  
# Swapping rows so that we can have our non zero row on the top of the matrix
def swap_rows(matrix, row1, row2):
    matrix[[row1, row2]] = matrix[[row2, row1]]
  
def make_pivot_one(matrix, pivot_row, col):
    pivot_element = matrix[pivot_row, col]
    matrix[pivot_row] //= pivot_element
    # print(pivot_element)
  
def eliminate_below(matrix, pivot_row, col):
    nrows = matrix.shape[0]
    pivot_element = matrix[pivot_row, col]
    for row in range(pivot_row + 1, nrows):
        factor = matrix[row, col]
        matrix[row] -= factor * matrix[pivot_row]
  
# Implementing above functions
def row_echelon_form(matrix):
    nrows = matrix.shape[0]
    ncols = matrix.shape[1]
    pivot_row = 0
# this will run for number of column times. If matrix has 3 columns this loop will run for 3 times
    for col in range(ncols):
        nonzero_row = find_nonzero_row(matrix, pivot_row, col)
        if nonzero_row is not None:
            swap_rows(matrix, pivot_row, nonzero_row)
            make_pivot_one(matrix, pivot_row, col)
            eliminate_below(matrix, pivot_row, col)
            pivot_row += 1
    return matrix
  
  
matrix = np.array([[2,-2,4,-2],[2,1,10,7],[-4,4,-8,4],[4,-1,14,6]])
print("Matrix Before Converting:")
print(matrix)
print()
result = row_echelon_form(matrix)
print("After Converting to Row Echelon Form:")
print(result)
if is_row_echelon_form(result):
    print("In REF")
else:
    print("Not in REF--------------->")


Output

Matrix Before Converting: 
[[ 2 -2 4 -2]
[ 2 1 10 7]
[-4 4 -8 4]
[ 4 -1 14 6]]
After Converting to Row Echelon Form:
[[ 1 -1 2 -1]
[ 0 1 2 3]
[ 0 0 0 1]
[ 0 0 0 0]]
In REF


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads