/** * Subtract matrix2 from matrix object on which this method is called * * @param Matrix $matrix2 * * @return Matrix Note that original matrix is left unchanged * @throws \DomainException * @throws \InvalidArgumentException */ public function subtract(Matrix $matrix2) { if ($this->rows !== $matrix2->numRows() || $this->columns !== $matrix2->numColumns()) { throw new \DomainException('Matrices are not the same size!'); } $newMatrix = []; foreach ($this->mainMatrix as $i => $row) { foreach ($row as $j => $column) { $newMatrix[$i][$j] = $column - $matrix2->getElementAt($i, $j); } } return new Matrix($newMatrix); }