I want to do matrix multiplication using array in PHP I have trying to do same but instead of matrix multiplication it just happening Simple multiplication as per output please help me to resolve it.
Here is my code:
<?php
$a1 = Array('0' => Array('0' => 1,'1' => 2),'1' => Array('0' => 4,'1' => 5));
$a2 = Array('0' => Array('0' => 7,'1' => 5),'1' => Array('0' => 3,'1' => 2));
$sumArray = array();
$result = array();
for($i=0; $i<=1; $i++)
{
for($j=0; $j<=1; $j++)
{
$result[$i][$j] = $a1[$i][$j] * $a2[$i][$j];
}
}
echo "<pre/>";
print_r($result);
?>
Output:
<?php
$a = Array('0' => Array('0' => 1,'1' => 2),'1' => Array('0' => 4,'1' => 5));
$b = Array('0' => Array('0' => 7,'1' => 5),'1' => Array('0' => 3,'1' => 2));
$sumArray = array();
$c = array();
for($i=0;$i<2;$i++) {
for($j=0;$j<2;$j++)
{
$c[$i][$j]=0;
for($k=0;$k<2;$k++)
{ $c[$i][$j]=$c[$i][$j]+($a[$i][$k]*$b[$k][$j]);
}
}
}
echo "<pre/>";
print_r($c);
?>
matrix multiplication is implemented the following way:
for i = 1..N
for j = 1..N
result[i][j] = 0.
for k = 1..N
result[i][j] += array1[i][k] * array2[j][k] // "row times column"
end for
end for
end for
I hope I got your question right. Matrix-Multiplication requires 3 for-loops.