Phpml\Math\Matrix::multiply PHP Method

multiply() public method

public multiply ( Matrix $matrix ) : Matrix
$matrix Matrix
return Matrix
    public function multiply(Matrix $matrix)
    {
        if ($this->columns != $matrix->getRows()) {
            throw InvalidArgumentException::inconsistentMatrixSupplied();
        }
        $product = [];
        $multiplier = $matrix->toArray();
        for ($i = 0; $i < $this->rows; ++$i) {
            $columns = $matrix->getColumns();
            for ($j = 0; $j < $columns; ++$j) {
                $product[$i][$j] = 0;
                for ($k = 0; $k < $this->columns; ++$k) {
                    $product[$i][$j] += $this->matrix[$i][$k] * $multiplier[$k][$j];
                }
            }
        }
        return new self($product, false);
    }

Usage Example

Beispiel #1
0
 public function testMatrixMultiplyByMatrix()
 {
     $matrix1 = new Matrix([[1, 2, 3], [4, 5, 6]]);
     $matrix2 = new Matrix([[7, 8], [9, 10], [11, 12]]);
     $product = [[58, 64], [139, 154]];
     $this->assertEquals($product, $matrix1->multiply($matrix2)->toArray());
 }