Sum of all Submatrices of a Given Matrix | JavaScript program to find the sum of all possible 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
let n = 3 ; function matrixSum ( arr ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) for ( let j = 0 ; j < n ; j ++ ) { let top_left = ( i + 1 ) * ( j + 1 ) ; let bottom_right = ( n - i ) * ( n - j ) ; sum += ( top_left * bottom_right * arr [ i ] [ j ] ) ; } return sum ; } let arr = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ; document . write ( matrixSum ( arr ) ) ;