Python – Get Matrix Mean
Last Updated :
11 May, 2023
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
test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]]
print ( "The original list : " + str (test_list))
res = [ sum (idx) / len (idx) for idx in zip ( * test_list)]
res = sum (res) / len (res)
print ( "Matrix Mean : " + str (res))
|
Output
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
from statistics import mean
test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]]
print ( "The original list : " + str (test_list))
res = [mean(idx) for idx in zip ( * test_list)]
res = mean(res)
print ( "Matrix Mean : " + str (res))
|
Output
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
import statistics
test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]]
print ( "The original list : " + str (test_list))
x = []
for i in test_list:
x.extend(i)
res = statistics.mean(x)
print ( "Matrix Mean : " + str (res))
|
Output
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 numpy as np
test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]]
arr = np.array(test_list)
res = np.mean(arr)
print ( "Matrix Mean : " + str (res))
|
Output
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
test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]]
print ( "The original matrix : " )
for row in test_list:
print (row)
total_sum = 0
count = 0
for row in test_list:
for num in row:
total_sum + = num
count + = 1
res = total_sum / count
print ( "Matrix Mean : " + str (res))
|
Output
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
test_list = [[ 5 , 6 , 3 ], [ 8 , 3 , 1 ], [ 9 , 10 , 4 ], [ 8 , 4 , 2 ]]
print ( "The original matrix : " )
for row in test_list:
print (row)
total_sum = functools. reduce (
lambda x, y: x + y, [num for row in test_list for num in row])
count = len ([num for row in test_list for num in row])
res = total_sum / count
print ( "Matrix Mean : " + str (res))
|
Output
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...