How to calculate the median of a matrix in Python

1 Answer

0 votes
def find_median_unsorted_matrix(matrix):
    # Step 1: Flatten the matrix into a single list
    elements = [val for row in matrix for val in row]

    # Step 2: Sort the elements
    elements.sort()

    # Step 3: Calculate median
    n = len(elements)
    if n % 2 == 1:
        # Odd number of elements: return middle element
        return elements[n // 2]
    else:
        # Even number of elements: return average of two middle elements
        return (elements[n // 2 - 1] + elements[n // 2]) / 2.0


matrix = [
    [5, 8, 9, 10],
    [1, 4, 6, 13],
    [7, 3, 0, 18],
    [6, 8, 9, 20]
]

median = find_median_unsorted_matrix(matrix)
print(f"Median of the matrix is: {median:.1f}")



"""
run:

Median of the matrix is: 7.5

"""

 



answered Oct 5 by avibootz
...