Loading content...
In data analysis and machine learning, computing statistical aggregations along specific dimensions of a matrix is a foundational operation. One of the most common aggregations is the arithmetic mean, which provides the central tendency of a set of values.
Given a matrix M of dimensions n × m (where n is the number of rows and m is the number of columns), you can compute the mean along two different axes:
Row-wise Mean (mode = 'row'): For each row i, compute the average of all elements in that row: $$\text{mean}i = \frac{1}{m} \sum{j=1}^{m} M_{ij}$$ This produces a vector of n mean values, one for each row.
Column-wise Mean (mode = 'column'): For each column j, compute the average of all elements in that column: $$\text{mean}j = \frac{1}{n} \sum{i=1}^{n} M_{ij}$$ This produces a vector of m mean values, one for each column.
Intuition:
Your Task: Write a Python function that computes the arithmetic mean of a matrix along a specified axis. The function should accept a matrix (2D list) and a mode string ('row' or 'column'), and return a list of mean values corresponding to the specified aggregation direction.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mode = 'column'[4.0, 5.0, 6.0]Computing the column-wise mean for a 3×3 matrix:
• Column 1: (1 + 4 + 7) / 3 = 12 / 3 = 4.0 • Column 2: (2 + 5 + 8) / 3 = 15 / 3 = 5.0 • Column 3: (3 + 6 + 9) / 3 = 18 / 3 = 6.0
The result is a list of 3 values, one mean for each column.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mode = 'row'[2.0, 5.0, 8.0]Computing the row-wise mean for a 3×3 matrix:
• Row 1: (1 + 2 + 3) / 3 = 6 / 3 = 2.0 • Row 2: (4 + 5 + 6) / 3 = 15 / 3 = 5.0 • Row 3: (7 + 8 + 9) / 3 = 24 / 3 = 8.0
The result is a list of 3 values, one mean for each row.
matrix = [[1, 2], [3, 4]]
mode = 'column'[2.0, 3.0]Computing the column-wise mean for a 2×2 matrix:
• Column 1: (1 + 3) / 2 = 4 / 2 = 2.0 • Column 2: (2 + 4) / 2 = 6 / 2 = 3.0
The result is a list of 2 values, one mean for each column.
Constraints