Back to Problems

Calculate Mean by Row or Column (easy)

Write a Python function that calculates the mean of a matrix either by row or by column, based on a given mode. The function should take a matrix (list of lists) and a mode ('row' or 'column') as input and return a list of means according to the specified mode.

Example

Example1:
        input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], mode = 'column'
        output: [4.0, 5.0, 6.0]
        reasoning: Calculating the mean of each column results in [(1+4+7)/3, (2+5+8)/3, (3+6+9)/3].
        
        Example 2:
        input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], mode = 'row'
        output: [2.0, 5.0, 8.0]
        reasoning: Calculating the mean of each row results in [(1+2+3)/3, (4+5+6)/3, (7+8+9)/3].

Calculate Mean by Row or Column

Calculating the mean of a matrix by row or column involves averaging the elements across the specified dimension. This operation provides insights into the distribution of values within the dataset, useful for data normalization and scaling.

Row Mean

The mean of a row is computed by summing all elements in the row and dividing by the number of elements. For row \(i\), the mean is: \[ \mu_{\text{row } i} = \frac{1}{n} \sum_{j=1}^{n} a_{ij} \] where \(a_{ij}\) is the matrix element in the \(i^{th}\) row and \(j^{th}\) column, and \(n\) is the total number of columns.

Column Mean

Similarly, the mean of a column is found by summing all elements in the column and dividing by the number of elements. For column \(j\), the mean is: \[ \mu_{\text{column } j} = \frac{1}{m} \sum_{i=1}^{m} a_{ij} \] where \(m\) is the total number of rows. This mathematical formulation helps in understanding how data is aggregated across different dimensions, a critical step in various data preprocessing techniques.
def calculate_matrix_mean(matrix: list[list[float]], mode: str) -> list[float]:
    if mode == 'column':
        return [sum(col) / len(matrix) for col in zip(*matrix)]
    elif mode == 'row':
        return [sum(row) / len(row) for row in matrix]
    else:
        raise ValueError("Mode must be 'row' or 'column'")

There’s no video solution available yet 😔, but you can be the first to submit one at: GitHub link.

Your Solution

Output will be shown here.