Skip to content

Commit

Permalink
Micro optimization for matrix multiplication (#255)
Browse files Browse the repository at this point in the history
* Micro optimization for matrix multiplication

* code cs fix

* added a comment block for the change
  • Loading branch information
MustafaKarabulut authored and akondas committed Mar 8, 2018
1 parent e156076 commit 0d80c78
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/Math/Matrix.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,24 @@ public function multiply(self $matrix): self
throw new InvalidArgumentException('Inconsistent matrix supplied');
}

$array1 = $this->toArray();
$array2 = $matrix->toArray();
$colCount = $matrix->columns;

/*
- To speed-up multiplication, we need to avoid use of array index operator [ ] as much as possible( See #255 for details)
- A combination of "foreach" and "array_column" works much faster then accessing the array via index operator
*/
$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];
foreach ($array1 as $row => $rowData) {
for ($col = 0; $col < $colCount; ++$col) {
$columnData = array_column($array2, $col);
$sum = 0;
foreach ($rowData as $key => $valueData) {
$sum += $valueData * $columnData[$key];
}

$product[$row][$col] = $sum;
}
}

Expand Down

0 comments on commit 0d80c78

Please sign in to comment.