public static Matrix average ( Matrix m , Dimension dim ) { Matrix averageMatrix = null ; if ( dim == Dimension . ALL ) { // Compute the average of all values in the matrix. double average = 0 ; for ( int i = 0 ; i < m . rows ( ) ; ++ i ) { for ( int j = 0 ; j < m . columns ( ) ; ++ j ) average += m . get ( i , j ) ; } averageMatrix = new ArrayMatrix ( 1 , 1 ) ; average = average / ( double ) ( m . rows ( ) * m . columns ( ) ) ; averageMatrix . set ( 1 , 1 , average ) ; } else if ( dim == Dimension . ROW ) { // Compute the average of each row in the matrix. averageMatrix = new ArrayMatrix ( m . rows ( ) , 1 ) ; for ( int i = 0 ; i < m . rows ( ) ; ++ i ) { double average = 0 ; for ( int j = 0 ; j < m . columns ( ) ; ++ j ) average += m . get ( i , j ) ; average = average / ( double ) m . columns ( ) ; averageMatrix . set ( i , 0 , average ) ; } } else if ( dim == Dimension . COLUMN ) { // Compute the average of each column in the matrix. averageMatrix = new ArrayMatrix ( 1 , m . columns ( ) ) ; for ( int i = 0 ; i < m . rows ( ) ; ++ i ) { for ( int j = 0 ; j < m . columns ( ) ; ++ j ) { double newValue = m . get ( i , j ) + averageMatrix . get ( 0 , j ) ; averageMatrix . set ( 0 , j , newValue ) ; } } for ( int i = 0 ; i < m . columns ( ) ; ++ i ) { double average = averageMatrix . get ( 0 , i ) ; average = average / ( double ) m . rows ( ) ; averageMatrix . set ( 0 , i , average ) ; } } return averageMatrix ; }
Return a matrix containing the averages for the dimension specificed .