Converting Matrix into Row Echelon Form in Python
Last Updated :
24 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
How to Convert Excel to XML Format in Python?
Python proves to be a powerful language when the requirement is to convert a file from one format to the other. It supports tools that can be employed to easily achieve the functionality. In this article, we'll find out how we will convert from an Excel file to Extensible terminology (XML) files wit
3 min read
Convert Excel to CSV in Python
In this article, we will be dealing with the conversion of Excel (.xlsx) file into .csv. Â There are two formats mostly used in Excel : (*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file.(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook). Let's Consider a dataset of a shopping store
3 min read
Python | Convert an HTML table into excel
MS Excel is a powerful tool for handling huge amounts of tabular data. It can be particularly useful for sorting, analyzing, performing complex calculations and visualizing data. In this article, we will discuss how to extract a table from a webpage and store it in Excel format. Step #1: Converting
2 min read
How to create a constant matrix in Python with NumPy?
A matrix represents a collection of numbers arranged in the order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. A constant matrix is a type of matrix whose elements are the same i.e. the element does not change irrespective of any index value th
4 min read
How to Convert a List to a DataFrame Row in Python?
In this article, we will discuss how to convert a list to a dataframe row in Python. Method 1: Using T function This is known as the Transpose function, this will convert the list into a row. Here each value is stored in one column. Syntax: pandas.DataFrame(list).T Example: Python3 # import pandas m
3 min read
Extracting rows using Pandas .iloc[] in Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. here we are learning how to Extract rows using Pandas .iloc[] in Python.Pandas .iloc[
7 min read
How to convert NumPy array to dictionary in Python?
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers givi
3 min read
How to Create a Decile Column in Python Polars
In this tutorial, we'll learn how to create a decile column using Python's Polars library. Deciles are a common way to divide data into ten equal parts, each containing 10% of the values. They are often used in statistics to understand data distribution, making them a powerful tool in data analysis.
2 min read
How to Convert NumPy Matrix to Array
In NumPy, a matrix is essentially a two-dimensional NumPy array with a special subclass. In this article, we will see how we can convert NumPy Matrix to Array. Also, we will see different ways to convert NumPy Matrix to Array. Convert Python NumPy Matrix to an ArrayBelow are the ways by which we can
3 min read
Matrix manipulation in Python
In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module "numpy". Operation on Matrix : 1. add() :- This function is used to perform eleme
4 min read