Created
November 24, 2020 17:59
-
-
Save poursadeqi/63545ef867d0ae0677faea25e7f5d751 to your computer and use it in GitHub Desktop.
matrix multiplier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace Something; | |
| class MatrixMultiplier | |
| { | |
| private $matrices; | |
| public function __construct(array $matrices) | |
| { | |
| $this->matrices = $matrices; | |
| } | |
| public function multiply(): array | |
| { | |
| $matricesLength = count($this->getMatrices()); | |
| if ($matricesLength < 2) { | |
| throw new \Exception('at least two matrix needs in order to multiply them'); | |
| } | |
| $result = $this->getNthMatrix(0); | |
| for ($i = 1; $i < $matricesLength; $i++) { | |
| $result = $this->multiply2Matrix($result, $this->getNthMatrix($i)); | |
| } | |
| return $result; | |
| } | |
| private function multiply2Matrix(array $leftMatrix, array $rightMatrix) | |
| { | |
| $result = []; | |
| $rightMatrixColumns = count($rightMatrix[0]); | |
| foreach ($leftMatrix as $index => $rows) { | |
| for ($j = 0; $j < $rightMatrixColumns; $j++) { | |
| $result[$index][$j] = $this->dot($rows, array_column($rightMatrix, $j)); | |
| } | |
| } | |
| return $result; | |
| } | |
| private function dot(array $rows, array $cols): float | |
| { | |
| $result = 0; | |
| foreach ($rows as $index => $row) { | |
| $result += $row * $cols[$index]; | |
| } | |
| return $result; | |
| } | |
| /** | |
| * @return array | |
| */ | |
| public function getMatrices(): array | |
| { | |
| return $this->matrices; | |
| } | |
| /** | |
| * @param int $i | |
| * @return mixed | |
| */ | |
| private function getNthMatrix(int $i) | |
| { | |
| return $this->getMatrices()[$i]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment