Skip to content

Instantly share code, notes, and snippets.

@poursadeqi
Created November 24, 2020 17:59
Show Gist options
  • Select an option

  • Save poursadeqi/63545ef867d0ae0677faea25e7f5d751 to your computer and use it in GitHub Desktop.

Select an option

Save poursadeqi/63545ef867d0ae0677faea25e7f5d751 to your computer and use it in GitHub Desktop.
matrix multiplier
<?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