Program for Rank of Matrix | Java program to find rank of a matrix ; function for exchanging two rows of a matrix ; function for finding rank of matrix ; Before we visit current row ' row ' , we make sure that mat [ row ] [ 0 ] , ... . mat [ row ] [ row - 1 ] are 0. Diagonal element is not zero ; This makes all entries of current column as 0 except entry ' mat [ row ] [ row ] ' ; 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 remvoe this column by swapping it with last column and reducing number of columns by 1. ; Find the non - zero element in current column ; Swap the row with non - zero element with this row . ; If we did not find any row with non - zero element in current columnm , then all values in this column are 0. ; Reduce number of columns ; Copy the last column here ; Process this row again ; Uncomment these lines to see intermediate results display ( mat , R , C ) ; printf ( " \n " ) ; ; Function to display a matrix ; Driver code
class GFG { static final int R = 3 ; static final int C = 3 ; 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 ; } } static int rankOfMatrix ( int mat [ ] [ ] ) { int rank = C ; for ( int row = 0 ; row < rank ; row ++ ) { if ( mat [ row ] [ row ] != 0 ) { for ( int col = 0 ; col < R ; col ++ ) { if ( col != row ) { double mult = ( double ) mat [ col ] [ row ] / mat [ row ] [ row ] ; for ( int i = 0 ; i < rank ; i ++ ) mat [ col ] [ i ] -= mult * mat [ row ] [ i ] ; } } } else { boolean reduce = true ; for ( int i = row + 1 ; i < R ; i ++ ) { if ( mat [ i ] [ row ] != 0 ) { swap ( mat , row , i , rank ) ; reduce = false ; break ; } } if ( reduce ) { rank -- ; for ( int i = 0 ; i < R ; i ++ ) mat [ i ] [ row ] = mat [ i ] [ rank ] ; } row -- ; } } return rank ; } 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 ( "NEW_LINE"); } } 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 ) ) ; } }