namespace Wmix\Matrix;
class Matrix
{
private $matrix = array();
private $n;
private $m;
public function __construct($n = null, $m = null, array $matrix = null)
{
$this->setSize($n, $m);
if ($matrix !== null) {
for ($i = 0; $i < $this->n; $i++) {
for ($j = 0; $j < $this->m; $j++) {
if (isset($matrix[$i]) && isset($matrix[$i][$j])){
$this->matrix[$i][$j] = (float) $matrix[$i][$j];
} else {
$this->matrix[$i][$j] = 0;
}
}
}
}
}
public function mul(Matrix $term)
{
list($nTerm, $mTerm) = $term->getSize();
if ($nTerm !== $this->m) {
throw new \InvalidArgumentException('The matrix is not agreed');
}
$result = new Matrix($this->n, $mTerm);
for ($i = 0; $i < $this->n; $i++) {
for ($j = 0; $j < $mTerm; $j++) {
$element = 0;
for ($e = 0; $e < $nTerm; $e++) {
$element += $this->get($i, $e) * $term->get($e, $j);
}
$result->set($i, $j, $element);
}
}
return $result;
}
public function setSize($n = null, $m = null)
{
if ($n !== null) {
$this->n = (int) $n;
}
if ($m !== null) {
$this->m = (int) $m;
}
}
public function getSize()
{
return array($this->n, $this->m);
}
public function get($i, $j)
{
if (isset($this->matrix[$i]) && isset($this->matrix[$i][$j])){
return $this->matrix[$i][$j];
}
throw new \InvalidArgumentException(sprintf('There is no element of matrix with indexes [%s][%s]', $i, $j));
}
public function set($i, $j, $value)
{
if ($i > $this->n || $i < 0) {
throw new \InvalidArgumentException('"i" should be less then "n" and more then zero');
}
if ($j > $this->m || $j < 0) {
throw new \InvalidArgumentException('"j" should be less then "m" and more then zero');
}
$this->matrix[(int) $i][(int) $j] = (float) $value;
}
public function out()
{
for ($i = 0; $i < $this->n; $i++) {
for ($j=0; $j < $this->m; $j++) {
echo $this->matrix[$i][$j], ' ';
}
echo "\n";
}
}
}
$m1 = new Matrix(2, 3, [
[4, 5, 6],
[7, 8, 9]
]);
$m2 = new Matrix(3, 2, [
[4, 5],
[7, 8],
[4, 5]
]);
echo var_dump($m1->mul($m2));