mirror of
https://github.com/Llewellynvdm/php-ml.git
synced 2024-11-25 06:17:34 +00:00
Micro optimization for matrix multiplication (#255)
* Micro optimization for matrix multiplication * code cs fix * added a comment block for the change
This commit is contained in:
parent
e156076539
commit
0d80c78c57
@ -142,15 +142,24 @@ class Matrix
|
|||||||
throw new InvalidArgumentException('Inconsistent matrix supplied');
|
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 = [];
|
$product = [];
|
||||||
$multiplier = $matrix->toArray();
|
foreach ($array1 as $row => $rowData) {
|
||||||
for ($i = 0; $i < $this->rows; ++$i) {
|
for ($col = 0; $col < $colCount; ++$col) {
|
||||||
$columns = $matrix->getColumns();
|
$columnData = array_column($array2, $col);
|
||||||
for ($j = 0; $j < $columns; ++$j) {
|
$sum = 0;
|
||||||
$product[$i][$j] = 0;
|
foreach ($rowData as $key => $valueData) {
|
||||||
for ($k = 0; $k < $this->columns; ++$k) {
|
$sum += $valueData * $columnData[$key];
|
||||||
$product[$i][$j] += $this->matrix[$i][$k] * $multiplier[$k][$j];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$product[$row][$col] = $sum;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user