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 9Output :Mean: 5        Median: 5Input : 1 1 1        2 2 2        4 4 4Output :Mean: 2        Median: 2`
`Mean of matrix is =    (sum of all elements of matrix)/   (total elements of matrix)Note that this definition doesn't requirematrix to be sorted and works for allmatrices.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++

 `// CPP program to find mean and median` `// of sorted square matrix.` `#include ` `using` `namespace` `std;`   `const` `int` `N = 4;`   `// Returns mean of a given matrix of` `// size n x n.` `double` `findMean(``int` `a[][N])` `{` `    ``int` `sum = 0;`   `    ``// total sum calculation of matrix` `    ``for` `(``int` `i=0; i

C

 `// C program to find mean and median` `// of sorted square matrix.` `#include `   `#define N 4` `// Returns mean of a given matrix of` `// size n x n.` `double` `findMean(``int` `a[][N])` `{` `    ``int` `sum = 0;`   `    ``// total sum calculation of matrix` `    ``for` `(``int` `i=0; i

Java

 `// Java program to find mean and median` `// of sorted square matrix.` `import` `java.io.*;`   `class` `GFG` `{` `    `  `// Returns mean of a given ` `// matrix of size n x n.` `static` `double` `findMean(``int` `a[][], ` `                    ``int` `n)` `{` `    ``int` `sum = ``0``;` `    ``int` `N=n;`   `    ``// total sum calculation of matrix` `    ``for` `(``int` `i = ``0``; i < N; i++)` `    ``for` `(``int` `j = ``0``; j < N; j++)` `        ``sum += a[i][j];`   `    ``return` `(``double``)sum / (N * N);` `}`   `// Function for calculating median` `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``;` `}`   `    ``// Driver Code` `    ``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));` `    ``}` `        `  `        `  `}`   `// This code is contributed by KRV.`

Python3

 `# Python3 program to find mean and median` `# of sorted square matrix.` `N ``=` `4`   `# Returns mean of a given matrix of` `# size n x n.` `def` `findMean(a):` `    `  `    ``summ ``=` `0` `    `  `    ``# total sum calculation of matrix` `    ``for` `i ``in` `range``(N):` `        ``for` `j ``in` `range``(N):` `            ``summ ``+``=` `a[i][j]` `    `  `    ``return` `summ``/``(N``*``N)`   `# Function for calculating median` `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`   `# Driver program` `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))`   `# This code is contributed by shubhamsingh10`

C#

 `// C# program to find mean and median` `// of sorted square matrix.` `using` `System;`   `class` `GFG {` `    `  `    ``// Returns mean of a given ` `    ``// matrix of size n x n.` `    ``static` `double` `findMean(``int` `[,]a, ``int` `n)` `    ``{` `        ``int` `sum = 0;` `        ``int` `N = n;` `    `  `        ``// total sum calculation of matrix` `        ``for` `(``int` `i = 0; i < N; i++)` `            ``for` `(``int` `j = 0; j < N; j++)` `                ``sum += a[i,j];` `    `  `        ``return` `(``double``)sum / (N * N);` `    ``}` `    `  `    ``// Function for calculating median` `    ``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;` `    ``}`   `    ``// Driver Code` `    ``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));` `    ``}` `        `  `}`   `// This code is contributed by Sam007.`

Javascript

 ``

PHP

 ``

Output

```Mean : 8.5
Median : 8.5

```

Time complexity: O(N2) as using two  for loops
Auxiliary Space: O(1)

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

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++

 `// C++ Program for the above approach` `#include ` `using` `namespace` `std;`   `// function to find out mean value` `double` `mean(vector>& 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;` `}`   `// Function to find out the media value` `double` `median(vector>& matrix) {` `    ``vector<``int``> flatten;` `    `  `    ``for` `(``const` `auto``& row : matrix) {` `        ``for` `(``int` `val : row) {` `            ``flatten.push_back(val);` `        ``}` `    ``}` `    `  `      ``// sorting the flatten array` `    ``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];` `    ``}` `}`   `// Driver Program to test above functions` `int` `main() {` `      ``// Given Matrix` `    ``vector> 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;` `}`   `// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL`

Java

 `import` `java.util.ArrayList;` `import` `java.util.Collections;` `import` `java.util.List;`   `public` `class` `Main {`   `    ``// function to find out mean value` `    ``static` `double` `mean(List > matrix)` `    ``{` `        ``int` `total = ``0``;` `        ``int` `count = matrix.size() * matrix.get(``0``).size();`   `        ``for` `(List row : matrix) {` `            ``for` `(``int` `val : row) {` `                ``total += val;` `            ``}` `        ``}`   `        ``return` `(``double``)total / count;` `    ``}`   `    ``// Function to find out the median value` `    ``static` `double` `median(List > matrix)` `    ``{` `        ``List flatten = ``new` `ArrayList<>();`   `        ``for` `(List row : matrix) {` `            ``for` `(``int` `val : row) {` `                ``flatten.add(val);` `            ``}` `        ``}`   `        ``// sorting the flatten array` `        ``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``);` `        ``}` `    ``}`   `    ``// Driver Program to test above functions` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// Given Matrix` `        ``List > 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);` `    ``}` `}` `// This code is contributed by akshitaguprzj3`

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``]`   `# Create a 3x3 matrix` `matrix ``=` `[[``1``, ``2``, ``3``], [``4``, ``5``, ``6``], [``7``, ``8``, ``9``]]`   `# Calculate mean and median` `mean_value ``=` `mean(matrix)` `median_value ``=` `median(matrix)`   `# Print the results` `print``(``"Mean:"``, mean_value)` `print``(``"Median:"``, median_value)`

C#

 `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;`   `class` `Program` `{` `    ``// Function to find out mean value` `    ``static` `double` `Mean(List> 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;` `    ``}`   `    ``// Function to find out the median value` `    ``static` `double` `Median(List> matrix)` `    ``{` `        ``List<``int``> flatten = ``new` `List<``int``>();`   `        ``foreach` `(``var` `row ``in` `matrix)` `        ``{` `            ``foreach` `(``int` `val ``in` `row)` `            ``{` `                ``flatten.Add(val);` `            ``}` `        ``}`   `        ``// Sorting the flatten list` `        ``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];` `        ``}` `    ``}`   `    ``// Driver Program to test above functions` `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``// Given Matrix` `        ``List> matrix = ``new` `List>` `        ``{` `            ``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}"``);` `    ``}` `}` `// This code is contributed by akshitaguprzj3`

Javascript

 `// Function to calculate the mean of a matrix` `function` `mean(matrix) {` `    ``let total = matrix.flat().reduce((sum, val) => sum + val, 0);` `    ``let count = matrix.length * matrix[0].length;` `    ``return` `total / count;` `}`   `// Function to calculate the median of a matrix` `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)];` `    ``}` `}`   `// Create a 3x3 matrix` `let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];`   `// Calculate mean and median` `let meanValue = mean(matrix);` `let medianValue = median(matrix);`   `// Print the results` `console.log(``"Mean:"``, meanValue);` `console.log(``"Median:"``, medianValue);`   `// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL`

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.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next
Similar Reads
Complete Tutorials