Converting Matrix into Row Echelon Form in Python
Last Updated :
28 Apr, 2025
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
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read