public function testMultiply() { $identity = $this->getIdentityMatrix($this->size); $array = array(); for ($i = 0; $i < $this->size; $i++) { for ($j = 0; $j < $this->size; $j++) { $array[$i][$j] = rand(); } } $matrix = new LL_Matrix($array); if ($this->strassen) { $result = $matrix->strassenMultiply($identity); } else { $result = $matrix->naiveMultiply($identity); } }
public function testMultiply() { $identity3 = $this->getIdentityMatrix(); $input = array(array(1, 2, 3), array(3, 2, 1), array(1, 2, 1)); $matrix = new LL_Matrix($input); $result = $matrix->multiply($identity3); for ($i = 0; $i < count($input); $i++) { for ($j = 0; $j < count($input[0]); $j++) { $this->assertEquals($result->get($i, $j), $input[$i][$j]); // identity multiplication should have no effect } } $result = $matrix->multiply(new LL_Matrix($input)); // test multiplying by itself. $this->assertNotEquals($result, false); $this->assertEquals($result->get(0, 0), 10); $this->assertEquals($result->get(0, 1), 12); $this->assertEquals($result->get(0, 2), 8); $this->assertEquals($result->get(1, 0), 10); $this->assertEquals($result->get(1, 1), 12); $this->assertEquals($result->get(1, 2), 12); $this->assertEquals($result->get(2, 0), 8); $this->assertEquals($result->get(2, 1), 8); $this->assertEquals($result->get(2, 2), 6); // test uneven shapes $input = array(array(1, 2, 3), array(0, 2, 0)); $input2 = array(array(1, 2), array(2, 2), array(1, 1)); $matrix = new LL_Matrix($input); $matrix2 = new LL_Matrix($input2); $this->assertEquals($matrix->multiply($matrix), false); $this->assertEquals($matrix2->multiply($matrix2), false); $result = $matrix->multiply($matrix2); $correct = array(array(8, 9), array(4, 4)); for ($i = 0; $i < count($correct); $i++) { for ($j = 0; $j < count($correct[0]); $j++) { $this->assertEquals($result->get($i, $j), $correct[$i][$j]); } } $result = $matrix2->multiply($matrix); $this->assertEquals($result->rows(), 3); $this->assertEquals($result->columns(), 3); }
public function naiveMultiply(LL_Matrix $matrix) { if (is_array($matrix)) { $matrix = new LL_Matrix($matrix); } if ($this->columns() != $matrix->rows()) { // impossible operation. return false; } $result = array(); for ($a = 0; $a < $this->rows(); $a++) { for ($b = 0; $b < $matrix->columns(); $b++) { $result[$a][$b] = 0; for ($i = 0; $i < $this->columns(); $i++) { $result[$a][$b] += $this->get($a, $i) * $matrix->get($i, $b); } } } return new LL_Matrix($result); }