Given a Matrix, Find its mean.
Input : test_list = [[5, 6, 7], [7, 5, 6]] Output : 6.0 Explanation : 36 / 6 = 6.0
Input : test_list = [[5, 6, 7, 4, 8]] Output : 6.0 Explanation : 30 / 5 = 6.0
Method #1 : Using list comprehension + sum() + len() + zip()
The combination of above functions can be used to solve this problem. In this, we perform the mean calculation using sum() and len(), zip() along with * operator does task of extracting each element of rows of matrix.
Python3
# Python3 code to demonstrate working of # Matrix Mean # Using list comprehension + sum() + len() + zip() # initializing lists test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]] # printing original list print ( "The original list : " + str (test_list)) # zip() to get all elements # sum() / len() gives mean # extracts column mean res = [ sum (idx) / len (idx) for idx in zip ( * test_list)] # extracts all elements mean res = sum (res) / len (res) # printing result print ( "Matrix Mean : " + str (res)) |
The original list : [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]] Matrix Mean : 5.25
Method #2 : Using mean() + zip() + list comprehension
This is another method in which this task can be performed. In this, we extract mean using inbuilt method of mean()
Python3
# Python3 code to demonstrate working of # Matrix Mean # Using mean() + zip() + list comprehension from statistics import mean # initializing lists test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]] # printing original list print ( "The original list : " + str (test_list)) # zip() to get all elements # mean() gives mean # extracts column mean res = [mean(idx) for idx in zip ( * test_list)] # extracts all elements mean res = mean(res) # printing result print ( "Matrix Mean : " + str (res)) |
The original list : [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]] Matrix Mean : 5.25
Method #3 : Using extend() and mean() method of statistics module
Python3
# Python3 code to demonstrate working of # Matrix Mean import statistics # initializing lists test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]] # printing original list print ( "The original list : " + str (test_list)) x = [] for i in test_list: x.extend(i) res = statistics.mean(x) # printing result print ( "Matrix Mean : " + str (res)) |
The original list : [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]] Matrix Mean : 5.25
Method #4: Using numpy
Here’s a step-by-step algorithm for calculating the mean of a matrix:
- Initialize the matrix as a list of lists.
- Convert the matrix to a NumPy array using np.array().
- Calculate the mean of the NumPy array using np.mean().
- Print the result to the console using print().
Python3
# Import the numpy library as np import numpy as np # Define the matrix as a list of lists test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]] # Converting the matrix to a NumPy array using np.array() arr = np.array(test_list) # Calculating the matrix using np.mean() res = np.mean(arr) # Printing esult to the console using print() print ( "Matrix Mean : " + str (res)) # This code is contributed by Vinay Pinjala |
The original list : [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]] Matrix Mean : 5.25
Time complexity: O(n^2). This is because there are two main operations that dominate the time complexity: initializing the matrix and converting it to a NumPy array. Initializing the matrix takes O(n^2) time, where n is the size of the matrix. Converting the matrix to a NumPy array also takes O(n^2) time. Calculating the mean of the NumPy array and printing the result to the console take constant time. Therefore, the overall time complexity is O(n^2).
Auxilairy space: O(n^2). This is because the matrix takes O(n^2) space in memory, and the NumPy array also takes O(n^2) space in memory. The mean of the NumPy array is stored in a single variable, which takes O(1) space. There are no additional data structures used in this algorithm. Therefore, the overall space complexity is O(n^2).
Method 5: Using nested loops
- Initialize a 2D list named test_list with integer values.
- Now printing the original matrix using a for loop to iterate through each row in test_list and print each row.
- Initializing two variables total_sum and count to zero.
- Using nested loops, iterate through each element in test_list, add the value of each element to total_sum, and increment the value of count by 1 for each element.
- Calculating the mean of the matrix by dividing total_sum by count and assign it to the variable res.
- Printing the calculated mean of the matrix as a string concatenated with “Matrix Mean : “.
Python3
# Python3 code to demonstrate working of # Matrix Mean # initializing matrix test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]] # Printing original matrix print ( "The original matrix : " ) for row in test_list: print (row) # Calculating mean # using nested loop total_sum = 0 count = 0 for row in test_list: for num in row: total_sum + = num count + = 1 # calculating mean res = total_sum / count # printing result print ( "Matrix Mean : " + str (res)) |
The original matrix : [5, 6, 3] [8, 3, 1] [9, 10, 4] [8, 4, 2] Matrix Mean : 5.25
Time complexity: O(n^2), where n is the number of elements in the matrix
Auxiliary space: O(1)
Method #7: Using the reduce() function from the functools module
Approach:
- Import the functools module using the import statement: import functools
- Define a lambda function that takes two arguments, x and y, and returns their sum: lambda x, y: x + y
- Use the reduce() function from functools to calculate the sum of all the elements in the matrix: total_sum = functools.reduce(lambda x, y: x + y, [num for row in test_list for num in row])
- Use the len() function to calculate the total number of elements in the matrix: count = len([num for row in test_list for num in row])
- Calculate the mean of the matrix by dividing the total_sum by the count: res = total_sum / count
- Print the result: print(“Matrix Mean : ” + str(res))
Python3
import functools # initializing matrix test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]] # printing original matrix print ( "The original matrix : " ) for row in test_list: print (row) # using reduce() function to calculate sum of all elements total_sum = functools. reduce ( lambda x, y: x + y, [num for row in test_list for num in row]) # calculating total number of elements in the matrix count = len ([num for row in test_list for num in row]) # calculating mean res = total_sum / count # printing result print ( "Matrix Mean : " + str (res)) |
The original matrix : [5, 6, 3] [8, 3, 1] [9, 10, 4] [8, 4, 2] Matrix Mean : 5.25
Time complexity: O(n^2), where n is the number of rows or columns in the matrix.
Auxiliary space: O(1), since we are only storing a few variables to calculate the mean.