Multiply Matrices
This algorithm multiplies two given matrices
class Matrix
{
public $_Matrix;
public $Rows;
public $Columns;
}
function MultiplyMatrices($firstMatrix, $secondMatrix)
{
$mult = array();
if ($firstMatrix->Columns != $secondMatrix->Rows)
return new Matrix();
for ($i = 0; $i < $firstMatrix->Rows; $i++)
for ($j = 0; $j < $secondMatrix->Columns; $j++)
{
$mult[$i][$j] = 0;
}
for ($i = 0; $i < $firstMatrix->Rows; $i++)
for ($j = 0; $j < $secondMatrix->Columns; $j++)
for ($k = 0; $k < $firstMatrix->Columns; $k++)
{
$mult[$i][$j] += $firstMatrix->_Matrix[$i][$k] * $secondMatrix->_Matrix[$k][$j];
}
$retVal = new Matrix();
$retVal->_Matrix = $mult;
$retVal->Rows = $firstMatrix->Rows;
$retVal->Columns = $secondMatrix->Columns;
return $retVal;
}
Example
$m1 = array();
$m1[0][0] = 3;
$m1[0][1] = -2;
$m1[0][2] = 5;
$m1[1][0] = 3;
$m1[1][1] = 0;
$m1[1][2] = 4;
$m2 = array();
$m2[0][0] = 2;
$m2[0][1] = 3;
$m2[1][0] = -9;
$m2[1][1] = 0;
$m2[2][0] = 0;
$m2[2][1] = 4;
$matrix1 = new Matrix();
$matrix1->_Matrix = $m1;
$matrix1->Rows = 2;
$matrix1->Columns = 3;
$matrix2 = new Matrix();
$matrix2->_Matrix = $m2;
$matrix2->Rows = 3;
$matrix2->Columns = 2;
$sumMatrix = MultiplyMatrices($matrix1, $matrix2);
Output
[0][0] = 24
[0][1] = 29
[1][0] = 6
[1][1] = 25