VOOZH about

URL: https://www.geeksforgeeks.org/dsa/mean-median-matrix/

⇱ Mean and Median of a matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mean and Median of a matrix

Last Updated : 13 Sep, 2023

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:


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 3x3 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.

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.

Comment