/** * Matrix test program. * * @param object IMatrix $mat The matrix to test. */ public static function test(IMatrix $mat) { printf("Matrix test program.\n"); try { $k = 0; for ($i = 0; $i < $mat->getNumRows(); ++$i) { for ($j = 0; $j < $mat->getNumCols(); ++$j) { $mat[array($i, $j)] = $k++; } } printf("%s\n", str($mat)); $mat = $mat->plus($mat); printf("%s\n", str($mat)); } catch (Exception $e) { printf("Caught %s\n", $e->getMessage()); } }
/** * Returns the sum of this dense matrix and the given dense matrix. * * @param object DenseMatrix $mat A dense matrix. * @return object DenseMatrix The sum. */ public function plus(IMatrix $mat) { if (!$mat instanceof self || $this->getNumRows() != $mat->getNumRows() || $this->getNumCols() != $mat->getNumCols()) { throw new ArgumentError(); } $result = new DenseMatrix($this->getNumRows(), $this->getNumCols()); for ($i = 0; $i < $this->getNumRows(); ++$i) { for ($j = 0; $j < $this->getNumCols(); ++$j) { $result[array($i, $j)] = $this[array($i, $j)] + $mat[array($i, $j)]; } } return $result; }
/** * Returns the product of this matrix and the specified matrix. * @param object IMatrix $mat The specified matrix. * @return object SparseMatrixAsVector * The product of this matrix and the specified matrix */ public function times(IMatrix $mat) { if ($this->numCols != $mat->numRows) { throw new ArgumentError(); } $matT = $mat->getTranspose(); $result = new SparseMatrixAsVector($this->numRows, $matT->numRows, $this->numRows + $matT->numRows); for ($iPosition = 0; $iPosition < $this->numberOfElements;) { $i = $this->array[$iPosition]->getRow(); for ($jPosition = 0; $jPosition < $matT->numberOfElements;) { $j = $matT->array[$jPosition]->getRow(); $sum = 0; $k1 = $iPosition; $k2 = $jPosition; while ($k1 < $this->numberOfElements && $this->array[$k1]->getRow() == $i && $k2 < $matT->numberOfElements && $matT->array[$k2]->getRow() == $j) { if ($this->array[$k1]->getColumn() < $matT->array[$k2]->getColumn()) { ++$k1; } elseif ($this->array[$k1]->getColumn() > $matT->array[$k2]->getColumn()) { ++$k2; } else { $sum += $this->array[$k1++]->getDatum() * $matT->array[$k2++]->getDatum(); } } if ($sum != 0) { $result[array($i, $j)] = $sum; } while ($jPosition < $matT->numberOfElements && $matT->array[$jPosition]->getRow() == $j) { ++$jPosition; } } while ($iPosition < $this->numberOfElements && $this->array[$iPosition]->getRow() == $i) { ++$iPosition; } } return $result; }