Program for Rank of Matrix | PHP 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 for displaying the matrix ; Driver code
< ? php $ R = 3 ; $ C = 3 ; 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 rankOfMatrix ( $ mat ) { global $ R , $ C ; $ rank = $ C ; for ( $ row = 0 ; $ row < $ rank ; $ row ++ ) { if ( $ mat [ $ row ] [ $ row ] ) { for ( $ col = 0 ; $ col < $ R ; $ col ++ ) { if ( $ col != $ row ) { $ mult = $ mat [ $ col ] [ $ row ] / $ mat [ $ row ] [ $ row ] ; for ( $ i = 0 ; $ i < $ rank ; $ i ++ ) $ mat [ $ col ] [ $ i ] -= $ mult * $ mat [ $ row ] [ $ i ] ; } } } else { $ reduce = true ; for ( $ i = $ row + 1 ; $ i < $ R ; $ i ++ ) { if ( $ mat [ $ i ] [ $ row ] ) { swap ( $ mat , $ row , $ i , $ rank ) ; $ reduce = false ; break ; } } if ( $ reduce ) { $ rank -- ; for ( $ i = 0 ; $ i < $ R ; $ i ++ ) $ mat [ $ i ] [ $ row ] = $ mat [ $ i ] [ $ rank ] ; } $ row -- ; } } return $ rank ; } function display ( $ mat , $ row , $ col ) { for ( $ i = 0 ; $ i < $ row ; $ i ++ ) { for ( $ j = 0 ; $ j < $ col ; $ j ++ ) print ( " ▁ $ mat [ $ i ] [ $ j ] " ) ; print ( " STRNEWLINE " ) ; } } $ mat = array ( array ( 10 , 20 , 10 ) , array ( -20 , -30 , 10 ) , array ( 30 , 50 , 0 ) ) ; print ( " Rank ▁ of ▁ the ▁ matrix ▁ is ▁ : ▁ " . rankOfMatrix ( $ mat ) ) ; ? >