Mean and Median of a matrix
Given a sorted matrix of size n*n. Calculate the mean and median of the matrix .
Examples:
Input : 1 2 3
4 5 6
7 8 9
Output :Mean: 5
Median: 5
Input : 1 1 1
2 2 2
4 4 4
Output :Mean: 2
Median: 2
Mean of matrix is =
(sum of all elements of matrix)/
(total elements of matrix)
Note that this definition doesn't require
matrix to be sorted and works for all
matrices.
Median of a sorted matrix is calculated as:
1. When n is odd
median is mat[n/2][n/2]
2. When n is even, median is average
of middle two elements.
Middle two elements can be found at indexes
a[(n-2)/2][n-1] and a[n/2][0]
If given matrix is unsorted, we can find its median by first sorting the matrix.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 4;
double findMean( int a[][N])
{
int sum = 0;
for ( int i=0; i<N; i++)
for ( int j=0; j<N; j++)
sum += a[i][j];
return ( double )sum/(N*N);
}
double findMedian( int a[][N])
{
if (N % 2 != 0)
return a[N/2][N/2];
if (N%2 == 0)
return (a[(N-2)/2][N-1] +
a[N/2][0])/2.0;
}
int main()
{
int a[N][N]= {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
cout << "Mean : " << findMean(a) << endl
<< "Median : " << findMedian(a) << endl;
return 0;
}
|
C
#include <stdio.h>
#define N 4
double findMean( int a[][N])
{
int sum = 0;
for ( int i=0; i<N; i++)
for ( int j=0; j<N; j++)
sum += a[i][j];
return ( double )sum/(N*N);
}
double findMedian( int a[][N])
{
if (N % 2 != 0)
return a[N/2][N/2];
if (N%2 == 0)
return (a[(N-2)/2][N-1] +
a[N/2][0])/2.0;
}
int main()
{
int a[N][N]= {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
printf ( "Mean : %f\n" ,findMean(a));
printf ( "Median : %f\n" ,findMedian(a));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static double findMean( int a[][],
int n)
{
int sum = 0 ;
int N=n;
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < N; j++)
sum += a[i][j];
return ( double )sum / (N * N);
}
static double findMedian( int a[][], int n)
{
int N = n;
if (N % 2 != 0 )
return a[N / 2 ][N / 2 ];
if (N % 2 == 0 )
return (a[(N - 2 ) / 2 ][ N - 1 ] +
a[ N / 2 ][ 0 ]) / ( 2.0 );
return 0 ;
}
public static void main (String[] args)
{
int a[][]= {{ 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 }};
int n = a.length;
System.out.println( "Mean : " +
findMean(a, n));
System.out.println( "Median : " +
findMedian(a, n));
}
}
|
Python3
N = 4
def findMean(a):
summ = 0
for i in range (N):
for j in range (N):
summ + = a[i][j]
return summ / (N * N)
def findMedian(a):
if (N % 2 ! = 0 ):
return a[N / / 2 ][N / / 2 ]
if (N % 2 = = 0 ):
return (a[(N - 2 ) / / 2 ][N - 1 ] + a[N / / 2 ][ 0 ]) / 2
a = [[ 1 , 2 , 3 , 4 ],[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],[ 13 , 14 , 15 , 16 ]]
print ( "Mean :" , findMean(a))
print ( "Median :" ,findMedian(a))
|
C#
using System;
class GFG {
static double findMean( int [,]a, int n)
{
int sum = 0;
int N = n;
for ( int i = 0; i < N; i++)
for ( int j = 0; j < N; j++)
sum += a[i,j];
return ( double )sum / (N * N);
}
static double findMedian( int [,]a, int n)
{
int N = n;
if (N % 2 != 0)
return a[N / 2,N / 2];
if (N % 2 == 0)
return ( a[(N - 2) / 2, (N - 1)] +
a[ N / 2, 0] ) / (2.0);
return 0;
}
public static void Main ()
{
int [,]a= { { 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16} };
int n = a.GetLength(0);
Console.WriteLine( "Mean : " +
findMean(a, n));
Console.WriteLine( "Median : " +
findMedian(a, n));
}
}
|
Javascript
<script>
function findMean(a, n)
{
var sum = 0;
var N = n;
for ( var i = 0; i < N; i++)
for ( var j = 0; j < N; j++)
sum += a[i][j];
return sum / (N * N);
}
function findMedian(a, n)
{
var N = n;
if (N % 2 != 0)
return a[N / 2][N / 2];
if (N % 2 == 0)
return (a[(N - 2) / 2][ N - 1] +
a[N / 2][0]) / (2.0);
return 0;
}
var a = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ] ];
var n = a.length;
document.write( "Mean : " +
findMean(a, n) + "<br>" );
document.write( "Median : " +
findMedian(a, n) + "<br>" );
</script>
|
PHP
<?php
$N = 4;
function findMean( $a )
{
global $N ;
$sum = 0;
for ( $i = 0; $i < $N ; $i ++)
for ( $j = 0; $j < $N ; $j ++)
$sum += $a [ $i ][ $j ];
return (double) $sum / ( $N * $N );
}
function findMedian( $a )
{
global $N ;
if ( $N % 2 != 0)
return $a [ $N / 2][ $N / 2];
if ( $N % 2 == 0)
return ( $a [( $N - 2) / 2][ $N - 1] +
$a [ $N / 2][0]) / 2.0;
}
$a = array ( array (1, 2, 3, 4),
array (5, 6, 7, 8),
array (9, 10, 11, 12),
array (13, 14, 15, 16));
echo "Mean : " , findMean( $a ), "\n" ,
"Median : " , findMedian( $a );
?>
|
Output
Mean : 8.5
Median : 8.5
Time complexity: O(N2) as using two for loops
Auxiliary Space: O(1)
METHOD 2:Using functions
APPROACH:
This Python program calculates the mean and median of a given matrix using functions. The program first defines two functions – mean() and median(), which take the matrix as an argument and return the calculated mean and median values, respectively. It then creates a 3×3 matrix and calls these functions to calculate the mean and median of the matrix. Finally, the program prints out the calculated mean and median values.
ALGORITHM:
- Define the mean() function that takes the matrix as an argument.
- Calculate the total sum of all the values in the matrix.
- Calculate the number of values in the matrix.
- Divide the total sum by the number of values to get the mean.
- Return the mean value.
- Define the median() function that takes the matrix as an argument.
- Flatten the matrix into a 1D list.
- Sort the list in ascending order.
- Calculate the length of the list.
- If the length of the list is even, calculate the average of the middle two values.
- If the length of the list is odd, return the middle value.
- Return the median value.
C++
#include <bits/stdc++.h>
using namespace std;
double mean(vector<vector< int >>& matrix) {
int total = 0;
int count = matrix.size() * matrix[0].size();
for ( const auto & row : matrix) {
for ( int val : row) {
total += val;
}
}
return static_cast < double >(total) / count;
}
double median(vector<vector< int >>& matrix) {
vector< int > flatten;
for ( const auto & row : matrix) {
for ( int val : row) {
flatten.push_back(val);
}
}
sort(flatten.begin(), flatten.end());
int n = flatten.size();
if (n % 2 == 0) {
return ( static_cast < double >(flatten[n/2]) + flatten[n/2-1]) / 2;
} else {
return flatten[n/2];
}
}
int main() {
vector<vector< int >> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
double mean_value = mean(matrix);
double median_value = median(matrix);
cout << "Mean: " << mean_value << endl;
cout << "Median: " << median_value << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
static double mean(List<List<Integer> > matrix)
{
int total = 0 ;
int count = matrix.size() * matrix.get( 0 ).size();
for (List<Integer> row : matrix) {
for ( int val : row) {
total += val;
}
}
return ( double )total / count;
}
static double median(List<List<Integer> > matrix)
{
List<Integer> flatten = new ArrayList<>();
for (List<Integer> row : matrix) {
for ( int val : row) {
flatten.add(val);
}
}
Collections.sort(flatten);
int n = flatten.size();
if (n % 2 == 0 ) {
return (( double )flatten.get(n / 2 )
+ flatten.get(n / 2 - 1 ))
/ 2 ;
}
else {
return flatten.get(n / 2 );
}
}
public static void main(String[] args)
{
List<List<Integer> > matrix = new ArrayList<>();
matrix.add( new ArrayList<>(List.of( 1 , 2 , 3 )));
matrix.add( new ArrayList<>(List.of( 4 , 5 , 6 )));
matrix.add( new ArrayList<>(List.of( 7 , 8 , 9 )));
double mean_value = mean(matrix);
double median_value = median(matrix);
System.out.println( "Mean: " + mean_value);
System.out.println( "Median: " + median_value);
}
}
|
Python3
def mean(matrix):
total = sum (val for row in matrix for val in row)
count = len (matrix) * len (matrix[ 0 ])
return total / count
def median(matrix):
flatten = [val for row in matrix for val in row]
flatten.sort()
n = len (flatten)
if n % 2 = = 0 :
return (flatten[n / / 2 ] + flatten[n / / 2 - 1 ]) / 2
else :
return flatten[n / / 2 ]
matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
mean_value = mean(matrix)
median_value = median(matrix)
print ( "Mean:" , mean_value)
print ( "Median:" , median_value)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static double Mean(List<List< int >> matrix)
{
int total = 0;
int count = matrix.Count * matrix[0].Count;
foreach ( var row in matrix)
{
foreach ( int val in row)
{
total += val;
}
}
return ( double )total / count;
}
static double Median(List<List< int >> matrix)
{
List< int > flatten = new List< int >();
foreach ( var row in matrix)
{
foreach ( int val in row)
{
flatten.Add(val);
}
}
flatten.Sort();
int n = flatten.Count;
if (n % 2 == 0)
{
return (( double )flatten[n / 2] + flatten[n / 2 - 1]) / 2;
}
else
{
return flatten[n / 2];
}
}
static void Main( string [] args)
{
List<List< int >> matrix = new List<List< int >>
{
new List< int > {1, 2, 3},
new List< int > {4, 5, 6},
new List< int > {7, 8, 9}
};
double meanValue = Mean(matrix);
double medianValue = Median(matrix);
Console.WriteLine($ "Mean: {meanValue}" );
Console.WriteLine($ "Median: {medianValue}" );
}
}
|
Javascript
function mean(matrix) {
let total = matrix.flat().reduce((sum, val) => sum + val, 0);
let count = matrix.length * matrix[0].length;
return total / count;
}
function median(matrix) {
let flatten = matrix.flat().sort((a, b) => a - b);
let n = flatten.length;
if (n % 2 === 0) {
return (flatten[n / 2] + flatten[n / 2 - 1]) / 2;
} else {
return flatten[Math.floor(n / 2)];
}
}
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let meanValue = mean(matrix);
let medianValue = median(matrix);
console.log( "Mean:" , meanValue);
console.log( "Median:" , medianValue);
|
Output
Mean: 5.0
Median: 5
Time Complexity: The time complexity of this program is O(nlogn) for sorting the list, where n is the total number of elements in the matrix.
Space Complexity: The space complexity of this program is O(n) for storing the flattened list, where n is the total number of elements in the matrix.
Last Updated :
13 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...