Program for Rank of Matrix
Last Updated :
23 Jul, 2025
What is rank of a matrix?
Rank of a matrix A of size M x N is defined as
- Maximum number of linearly independent column vectors in the matrix or
- Maximum number of linearly independent row vectors in the matrix.
Example:
Input: mat[][] = {{10, 20, 10},
{20, 40, 20},
{30, 50, 0}}
Output: Rank is 2
Explanation: Ist and IInd rows are linearly dependent.
But Ist and 3rd or IInd and IIIrd are
independent.
Input: mat[][] = {{10, 20, 10},
{-20, -30, 10},
{30, 50, 0}}
Output: Rank is 2
Explanation: Ist and IInd rows are linearly independent.
So rank must be atleast 2. But all three rows
are linearly dependent (the first is equal to
the sum of the second and third) so the rank
must be less than 3.
In other words rank of A is the largest order of any non-zero minor in A where order of a minor is the side-length of the square sub-matrix of which it is determinant.
So if M < N then maximum rank of A can be M else it can be N, in general rank of matrix can’t be greater than min(M, N).
The rank of a matrix would be zero only if the matrix had no non-zero elements. If a matrix had even one non-zero element, its minimum rank would be one.
How to find Rank?
The idea is based on conversion to Row echelon form.
1) Let the input matrix be mat[][]. Initialize rank equals
to number of columns
// Before we visit row 'row', traversal of previous
// rows make sure that mat[row][0],....mat[row][row-1]
// are 0.
2) Do following for row = 0 to rank-1.
a) If mat[row][row] is not zero, make all elements of
current column as 0 except the element mat[row][row]
by finding appropriate multiplier and adding a the
multiple of row 'row'
b) Else (mat[row][row] is zero). Two cases arise:
(i) If there is a row below it with non-zero entry in
same column, then swap current 'row' and that row.
(ii) If all elements in current column below mat[r][row]
are 0, then remove this column by swapping it with
last column and reducing number of rank by 1.
Reduce row by 1 so that this row is processed again.
3) Number of remaining columns is rank of matrix.
Example:
Input: mat[][] = {{10, 20, 10},
{-20, -30, 10},
{30, 50, 0}}
row = 0:
Since mat[0][0] is not 0, we are in case 2.a of above algorithm.
We set all entries of 0'th column as 0 (except entry mat[0][0]).
To do this, we subtract R1*(-2) from R2, i.e., R2 --> R2 - R1*(-2)
mat[][] = {{10, 20, 10},
{ 0, 10, 30},
{30, 50, 0}}
And subtract R1*3 from R3, i.e., R3 --> R3 - R1*3
mat[][] = {{10, 20, 10},
{ 0, 10, 30},
{ 0, -10, -30}}
row = 1:
Since mat[1][1] is not 0, we are in case 2.a of above algorithm.
We set all entries of 1st column as 0 (except entry mat[1][1]).
To do this, we subtract R2*2 from R1, i.e., R1 --> R1 - R2*2
mat[][] = {{10, 0, -50},
{ 0, 10, 30},
{ 0, -10, -30}}
And subtract R2*(-1) from R3, i.e., R3 --> R3 - R2*(-1)
mat[][] = {{10, 0, -50},
{ 0, 10, 30},
{ 0, 0, 0}}
row = 2:
Since mat[2][2] is 0, we are in case 2.b of above algorithm.
Since there is no row below it swap. We reduce the rank by 1 and
keep row as 2.
The loop doesn't iterate next time because loop termination condition
row <= rank-1 returns false.
Below is the implementation of above idea.
C++
// C++ program to find rank of a matrix
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
/* function for exchanging two rows of
a matrix */
void swap(int mat[R][C], int row1, int row2,
int col)
{
for (int i = 0; i < col; i++)
{
int temp = mat[row1][i];
mat[row1][i] = mat[row2][i];
mat[row2][i] = temp;
}
}
// Function to display a matrix
void display(int mat[R][C], int row, int col);
/* function for finding rank of matrix */
int rankOfMatrix(int mat[R][C])
{
int rank = C;
for (int row = 0; row < rank; row++)
{
// Before we visit current row 'row', we make
// sure that mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if (mat[row][row])
{
for (int col = 0; col < R; col++)
{
if (col != row)
{
// This makes all entries of current
// column as 0 except entry 'mat[row][row]'
double mult = (double)mat[col][row] /
mat[row][row];
for (int i = 0; i < rank; i++)
mat[col][i] -= mult * mat[row][i];
}
}
}
// Diagonal element is already zero. Two cases
// arise:
// 1) If there is a row below it with non-zero
// entry, then swap this row with that row
// and process that row
// 2) If all elements in current column below
// mat[r][row] are 0, then remove this column
// by swapping it with last column and
// reducing number of columns by 1.
else
{
bool reduce = true;
/* Find the non-zero element in current
column */
for (int i = row + 1; i < R; i++)
{
// Swap the row with non-zero element
// with this row.
if (mat[i][row])
{
swap(mat, row, i, rank);
reduce = false;
break ;
}
}
// If we did not find any row with non-zero
// element in current column, then all
// values in this column are 0.
if (reduce)
{
// Reduce number of columns
rank--;
// Copy the last column here
for (int i = 0; i < R; i ++)
mat[i][row] = mat[i][rank];
}
// Process this row again
row--;
}
// Uncomment these lines to see intermediate results
// display(mat, R, C);
// printf("\n");
}
return rank;
}
/* function for displaying the matrix */
void display(int mat[R][C], int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
printf(" %d", mat[i][j]);
printf("\n");
}
}
// Driver program to test above functions
int main()
{
int mat[][3] = {{10, 20, 10},
{-20, -30, 10},
{30, 50, 0}};
printf("Rank of the matrix is : %d",
rankOfMatrix(mat));
return 0;
}
Java
// Java program to find rank of a matrix
import java.util.*;
class GFG {
static final int R = 3;
static final int C = 3;
// function for exchanging two rows
// of a matrix
static void swap(int mat[][],
int row1, int row2, int col)
{
for (int i = 0; i < col; i++)
{
int temp = mat[row1][i];
mat[row1][i] = mat[row2][i];
mat[row2][i] = temp;
}
}
// Function to display a matrix
static void display(int mat[][],
int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
System.out.print(" "
+ mat[i][j]);
System.out.print("\n");
}
}
// function for finding rank of matrix
static int rankOfMatrix(int mat[][])
{
int rank = C;
for (int row = 0; row < rank; row++)
{
// Before we visit current row
// 'row', we make sure that
// mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if (mat[row][row] != 0)
{
for (int col = 0; col < R; col++)
{
if (col != row)
{
// This makes all entries
// of current column
// as 0 except entry
// 'mat[row][row]'
double mult =
(double)mat[col][row] /
mat[row][row];
for (int i = 0; i < rank; i++)
mat[col][i] -= mult
* mat[row][i];
}
}
}
// Diagonal element is already zero.
// Two cases arise:
// 1) If there is a row below it
// with non-zero entry, then swap
// this row with that row and process
// that row
// 2) If all elements in current
// column below mat[r][row] are 0,
// then remove this column by
// swapping it with last column and
// reducing number of columns by 1.
else
{
boolean reduce = true;
// Find the non-zero element
// in current column
for (int i = row + 1; i < R; i++)
{
// Swap the row with non-zero
// element with this row.
if (mat[i][row] != 0)
{
swap(mat, row, i, rank);
reduce = false;
break ;
}
}
// If we did not find any row with
// non-zero element in current
// column, then all values in
// this column are 0.
if (reduce)
{
// Reduce number of columns
rank--;
// Copy the last column here
for (int i = 0; i < R; i ++)
mat[i][row] = mat[i][rank];
}
// Process this row again
row--;
}
// Uncomment these lines to see
// intermediate results display(mat, R, C);
// printf("\n");
}
return rank;
}
// Driver code
public static void main (String[] args)
{
int mat[][] = {{10, 20, 10},
{-20, -30, 10},
{30, 50, 0}};
System.out.print("Rank of the matrix is : "
+ rankOfMatrix(mat));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python 3 program to find rank of a matrix
class rankMatrix(object):
def __init__(self, Matrix):
self.R = len(Matrix)
self.C = len(Matrix[0])
# Function for exchanging two rows of a matrix
def swap(self, Matrix, row1, row2, col):
for i in range(col):
temp = Matrix[row1][i]
Matrix[row1][i] = Matrix[row2][i]
Matrix[row2][i] = temp
# Function to Display a matrix
def Display(self, Matrix, row, col):
for i in range(row):
for j in range(col):
print (" " + str(Matrix[i][j]))
print ('\n')
# Find rank of a matrix
def rankOfMatrix(self, Matrix):
rank = self.C
for row in range(0, rank, 1):
# Before we visit current row
# 'row', we make sure that
# mat[row][0],....mat[row][row-1]
# are 0.
# Diagonal element is not zero
if Matrix[row][row] != 0:
for col in range(0, self.R, 1):
if col != row:
# This makes all entries of current
# column as 0 except entry 'mat[row][row]'
multiplier = (Matrix[col][row] /
Matrix[row][row])
for i in range(rank):
Matrix[col][i] -= (multiplier *
Matrix[row][i])
# Diagonal element is already zero.
# Two cases arise:
# 1) If there is a row below it
# with non-zero entry, then swap
# this row with that row and process
# that row
# 2) If all elements in current
# column below mat[r][row] are 0,
# then remove this column by
# swapping it with last column and
# reducing number of columns by 1.
else:
reduce = True
# Find the non-zero element
# in current column
for i in range(row + 1, self.R, 1):
# Swap the row with non-zero
# element with this row.
if Matrix[i][row] != 0:
self.swap(Matrix, row, i, rank)
reduce = False
break
# If we did not find any row with
# non-zero element in current
# column, then all values in
# this column are 0.
if reduce:
# Reduce number of columns
rank -= 1
# copy the last column here
for i in range(0, self.R, 1):
Matrix[i][row] = Matrix[i][rank]
# process this row again
row -= 1
# self.Display(Matrix, self.R,self.C)
return (rank)
# Driver Code
if __name__ == '__main__':
Matrix = [[10, 20, 10],
[-20, -30, 10],
[30, 50, 0]]
RankMatrix = rankMatrix(Matrix)
print ("Rank of the matrix is:",
(RankMatrix.rankOfMatrix(Matrix)))
# This code is contributed by Vikas Chitturi
C#
// C# program to find rank of a matrix
using System;
class GFG {
static int R = 3;
static int C = 3;
// function for exchanging two rows
// of a matrix
static void swap(int [,]mat,
int row1, int row2, int col)
{
for (int i = 0; i < col; i++)
{
int temp = mat[row1,i];
mat[row1,i] = mat[row2,i];
mat[row2,i] = temp;
}
}
// Function to display a matrix
static void display(int [,]mat,
int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
Console.Write(" "
+ mat[i,j]);
Console.Write("\n");
}
}
// function for finding rank of matrix
static int rankOfMatrix(int [,]mat)
{
int rank = C;
for (int row = 0; row < rank; row++)
{
// Before we visit current row
// 'row', we make sure that
// mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if (mat[row,row] != 0)
{
for (int col = 0; col < R; col++)
{
if (col != row)
{
// This makes all entries
// of current column
// as 0 except entry
// 'mat[row][row]'
double mult =
(double)mat[col,row] /
mat[row,row];
for (int i = 0; i < rank; i++)
mat[col,i] -= (int) mult
* mat[row,i];
}
}
}
// Diagonal element is already zero.
// Two cases arise:
// 1) If there is a row below it
// with non-zero entry, then swap
// this row with that row and process
// that row
// 2) If all elements in current
// column below mat[r][row] are 0,
// then remove this column by
// swapping it with last column and
// reducing number of columns by 1.
else
{
bool reduce = true;
// Find the non-zero element
// in current column
for (int i = row + 1; i < R; i++)
{
// Swap the row with non-zero
// element with this row.
if (mat[i,row] != 0)
{
swap(mat, row, i, rank);
reduce = false;
break ;
}
}
// If we did not find any row with
// non-zero element in current
// column, then all values in
// this column are 0.
if (reduce)
{
// Reduce number of columns
rank--;
// Copy the last column here
for (int i = 0; i < R; i ++)
mat[i,row] = mat[i,rank];
}
// Process this row again
row--;
}
// Uncomment these lines to see
// intermediate results display(mat, R, C);
// printf("\n");
}
return rank;
}
// Driver code
public static void Main ()
{
int [,]mat = {{10, 20, 10},
{-20, -30, 10},
{30, 50, 0}};
Console.Write("Rank of the matrix is : "
+ rankOfMatrix(mat));
}
}
// This code is contributed by nitin mittal
JavaScript
<script>
// javascript program to find rank of a matrix
var R = 3;
var C = 3;
// function for exchanging two rows
// of a matrix
function swap(mat, row1 , row2 , col)
{
for (i = 0; i < col; i++)
{
var temp = mat[row1][i];
mat[row1][i] = mat[row2][i];
mat[row2][i] = temp;
}
}
// Function to display a matrix
function display(mat,row , col)
{
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
document.write(" "
+ mat[i][j]);
document.write('<br>');
}
}
// function for finding rank of matrix
function rankOfMatrix(mat)
{
var rank = C;
for (row = 0; row < rank; row++)
{
// Before we visit current row
// 'row', we make sure that
// mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if (mat[row][row] != 0)
{
for (col = 0; col < R; col++)
{
if (col != row)
{
// This makes all entries
// of current column
// as 0 except entry
// 'mat[row][row]'
var mult =
mat[col][row] /
mat[row][row];
for (i = 0; i < rank; i++)
mat[col][i] -= mult
* mat[row][i];
}
}
}
// Diagonal element is already zero.
// Two cases arise:
// 1) If there is a row below it
// with non-zero entry, then swap
// this row with that row and process
// that row
// 2) If all elements in current
// column below mat[r][row] are 0,
// then remove this column by
// swapping it with last column and
// reducing number of columns by 1.
else
{
reduce = true;
// Find the non-zero element
// in current column
for (var i = row + 1; i < R; i++)
{
// Swap the row with non-zero
// element with this row.
if (mat[i][row] != 0)
{
swap(mat, row, i, rank);
reduce = false;
break ;
}
}
// If we did not find any row with
// non-zero element in current
// column, then all values in
// this column are 0.
if (reduce)
{
// Reduce number of columns
rank--;
// Copy the last column here
for (i = 0; i < R; i ++)
mat[i][row] = mat[i][rank];
}
// Process this row again
row--;
}
// Uncomment these lines to see
// intermediate results display(mat, R, C);
// printf(<br>);
}
return rank;
}
// Driver code
var mat = [[10, 20, 10],
[-20, -30, 10],
[30, 50, 0]];
document.write("Rank of the matrix is : "
+ rankOfMatrix(mat));
// This code is contributed by Amit Katiyar
</script>
PHP
<?php
// PHP program to find rank of a matrix
$R = 3;
$C = 3;
/* function for exchanging two rows of
a matrix */
function swap(&$mat, $row1, $row2, $col)
{
for ($i = 0; $i < $col; $i++)
{
$temp = $mat[$row1][$i];
$mat[$row1][$i] = $mat[$row2][$i];
$mat[$row2][$i] = $temp;
}
}
/* function for finding rank of matrix */
function rankOfMatrix($mat)
{
global $R, $C;
$rank = $C;
for ($row = 0; $row < $rank; $row++)
{
// Before we visit current row 'row', we make
// sure that mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if ($mat[$row][$row])
{
for ($col = 0; $col < $R; $col++)
{
if ($col != $row)
{
// This makes all entries of current
// column as 0 except entry 'mat[row][row]'
$mult = $mat[$col][$row] / $mat[$row][$row];
for ($i = 0; $i < $rank; $i++)
$mat[$col][$i] -= $mult * $mat[$row][$i];
}
}
}
// Diagonal element is already zero. Two cases
// arise:
// 1) If there is a row below it with non-zero
// entry, then swap this row with that row
// and process that row
// 2) If all elements in current column below
// mat[r][row] are 0, then remove this column
// by swapping it with last column and
// reducing number of columns by 1.
else
{
$reduce = true;
/* Find the non-zero element in current
column */
for ($i = $row + 1; $i < $R; $i++)
{
// Swap the row with non-zero element
// with this row.
if ($mat[$i][$row])
{
swap($mat, $row, $i, $rank);
$reduce = false;
break ;
}
}
// If we did not find any row with non-zero
// element in current column, then all
// values in this column are 0.
if ($reduce)
{
// Reduce number of columns
$rank--;
// Copy the last column here
for ($i = 0; $i < $R; $i++)
$mat[$i][$row] = $mat[$i][$rank];
}
// Process this row again
$row--;
}
// Uncomment these lines to see intermediate results
// display(mat, R, C);
// printf("\n");
}
return $rank;
}
/* function for displaying the matrix */
function display($mat, $row, $col)
{
for ($i = 0; $i < $row; $i++)
{
for ($j = 0; $j < $col; $j++)
print(" $mat[$i][$j]");
print("\n");
}
}
// Driver code
$mat = array(array(10, 20, 10),
array(-20, -30, 10),
array(30, 50, 0));
print("Rank of the matrix is : ".rankOfMatrix($mat));
// This code is contributed by mits
?>
OutputRank of the matrix is : 2
Time complexity: O(row x col x rank).
Auxiliary Space: O(1)
Since above rank calculation method involves floating point arithmetic, it may produce incorrect results if the division goes beyond precision. There are other methods to handle.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem