How to calculate the median of a matrix in PHP

1 Answer

0 votes
function findMedianUnsortedMatrix($matrix) {
    $elements = [];

    // Flatten the matrix
    foreach ($matrix as $row) {
        foreach ($row as $val) {
            $elements[] = $val;
        }
    }

    // Sort the elements
    sort($elements);

    // Calculate median
    $n = count($elements);
    if ($n % 2 == 1) {
        // Odd number of elements: return middle element
        return $elements[intdiv($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 = findMedianUnsortedMatrix($matrix);
printf("Median of the matrix is: %.1f\n", $median);



/*
run:

Median of the matrix is: 7.5

*/

 



answered Oct 5, 2025 by avibootz
edited Oct 5, 2025 by avibootz
...