How to implement matrix multiplication in PHP

2 Answers

0 votes
// Multiply rows of A by columns of B.

// Print a 2D array
function PrintMatrix($arr2d) {
    $rows = count($arr2d);
    $cols = count($arr2d[0]);

    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            printf("%4d", $arr2d[$i][$j]);
        }
        echo PHP_EOL;
    }
}

// Calc: compute dot product of row i of A and column j of B
function Calc($a, $b, $i, $j) {
    $sum = 0;
    $size = count($a[0]); // number of columns in A

    for ($x = 0; $x < $size; $x++) {
        $sum += $a[$i][$x] * $b[$x][$j];
    }

    return $sum;
}

// Main logic (formerly Main method)
$a = [
    [1, 8, 5],
    [6, 7, 1],
    [8, 7, 6]
];

$b = [
    [4, 8, 1],
    [6, 5, 3],
    [4, 6, 5]
];

$c = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
];

PrintMatrix($a);
echo PHP_EOL;
PrintMatrix($b);
echo PHP_EOL;

// c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])

for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        $c[$i][$j] = Calc($a, $b, $i, $j);
    }
}

PrintMatrix($c);


/*
run:
      
   1   8   5
   6   7   1
   8   7   6
  
   4   8   1
   6   5   3
   4   6   5
  
  72  78  50
  70  89  32
  98 135  59
  
*/

 



answered Feb 29, 2016 by avibootz
edited 3 days ago by avibootz
0 votes
// Multiply rows of A by columns of B.

// Print a 2D array
function PrintMatrix($arr2d) {
    $rows = count($arr2d);
    $cols = count($arr2d[0]);

    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            printf("%4d", $arr2d[$i][$j]);
        }
        echo PHP_EOL;
    }
}

// multiple_matrix: compute C = A × B
function multiple_matrix($a, $b, &$c) {
    $rows = count($a);
    $cols = count($b[0]);
    $inner = count($a[0]); // number of columns in A

    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            for ($k = 0; $k < $inner; $k++) {
                $c[$i][$j] = $c[$i][$j] + $a[$i][$k] * $b[$k][$j];
            }
        }
    }
}

// Main logic (formerly Main method)
$a = [
    [1, 8, 5],
    [6, 7, 1],
    [8, 7, 6]
];

$b = [
    [4, 8, 1],
    [6, 5, 3],
    [4, 6, 5]
];

$c = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
];

PrintMatrix($a);
echo PHP_EOL;
PrintMatrix($b);
echo PHP_EOL;

// c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])

multiple_matrix($a, $b, $c);
PrintMatrix($c);



/*
run:
      
   1   8   5
   6   7   1
   8   7   6
  
   4   8   1
   6   5   3
   4   6   5
  
  72  78  50
  70  89  32
  98 135  59
  
*/

 



answered Feb 29, 2016 by avibootz
edited 3 days ago by avibootz
...