Sum of all Submatrices of a Given Matrix | Function to find the sum of all possible submatrices of a given Matrix ; Variable to store the required sum ; Nested loop to find the number of submatrices , each number belongs to ; Number of ways to choose from top - left elements ; Number of ways to choose from bottom - right elements ; Driver Code
< ? php function matrixSum ( $ arr ) { $ n = 3 ; $ sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { $ top_left = ( $ i + 1 ) * ( $ j + 1 ) ; $ bottom_right = ( $ n - $ i ) * ( $ n - $ j ) ; $ sum += ( $ top_left * $ bottom_right * $ arr [ $ i ] [ $ j ] ) ; } return $ sum ; } $ arr = array ( array ( 1 , 1 , 1 ) , array ( 1 , 1 , 1 ) , array ( 1 , 1 , 1 ) ) ; echo matrixSum ( $ arr ) ; ? >