public function product(Matrix $matrix) { if ($this->columns !== $matrix->getRows()) { return false; } $c = $matrix->getColumns(); $result = new Matrix($this->rows, $c); for ($i = 0; $i < $this->rows; ++$i) { for ($j = 0; $j < $c; ++$j) { $sum = 0; for ($k = 0; $k < $this->columns; ++$k) { $sum += $this->matrix[$i][$k] * $matrix->getElement($k, $j); } $result->setElement($i, $j, $sum); } } return $result; }
/** * Create a matrix from an array of doubles. * * @param * sourceMatrix * An array of doubles. */ public static function matrixFromDoubles(array $sourceMatrix) { $out = new Matrix(count($sourceMatrix), count($sourceMatrix[0])); for ($r = 0; $r < $out->getRows(); ++$r) { for ($c = 0; $c < $out->getCols(); ++$c) { $out->set($r, $c, $sourceMatrix[$r][$c]); } } return $out; }
public function testSize() { $matrix = new Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]); $this->assertEquals(3, $matrix->getRows()); $this->assertEquals(4, $matrix->getCols()); }