0

I have 2 arrays which represent matrix with the new format:

$array1 = Array( Array(1, 2) , Array(3, 4) );
$array2 = Array( Array(0, 1) , Array(5, 6) );

This is what i tried:

$array = Array();

foreach ($array2 as $idB => $columnsB) {
    for($i = 0; $i < count($columnsB); $i++) {
        $array[$i][] = $columnsB[$i];  
    }
}

$productArray = Array();

for ($i = 0; $i < count($array1); $i++) {
    for ($j = 0; $j < count($array); $j++) {
        $productArray[$i][$j] = $array1[$i][$j] * $array[$j][$i];
    }
}

Expected result :

$array = Array(0 => Array(10, 13), 1 => Array(20,27));

But, it is not correct because is only takes line1 from first array and column2 from seond array

hakre
  • 193,403
  • 52
  • 435
  • 836
OsomA
  • 155
  • 1
  • 18

3 Answers3

0

Using PHP 5.5's array_column() function to simplify access to $array2:

$array1 = array( array(1, 2), array(3, 4) );
$array2 = array( array(0, 1), array(5, 6) );

$rows = count($array1);
$columns = count($array1[0]);

$result = [];
for($row = 0; $row < $rows; ++$row) {
    $rowData = $array1[$row];
    for($column = 0; $column < $columns; ++$column) {
        $columnData = array_column($array2,$column);
        $v = 0;
        foreach($rowData as $key => $valueData) {
            $v += $valueData * $columnData[$key];
        }
        $result[$row][$column] = $v;
    }
}

If you don't have PHP 5.5

function array_column($array, $column) {
    return array_map(
        function($value) use ($column) {
            return $value[$column];
        },
        $array
    );
}
nl-x
  • 11,762
  • 7
  • 33
  • 61
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

You need additional loop, to sum single products:

for ($i = 0; $i < count($array1); $i++) {
    for ($j = 0; $j < count($array); $j++) {
        for ($k = 0; $k < count ($array[$j]); $k++) {
           $productArray[$i][$j] += $array1[$i][$k] * $array[$j][$k];
        }
    }
}
ziollek
  • 1,973
  • 1
  • 12
  • 10
-1
function matrixmult($m1,$m2){
    $r=count($m1);
    $c=count($m2[0]);
    $p=count($m2);
    if(count($m1[0])!=$p){throw new Exception('Incompatible matrixes');}
    $m3=array();
    for ($i=0;$i< $r;$i++){
        for($j=0;$j<$c;$j++){
            $m3[$i][$j]=0;
            for($k=0;$k<$p;$k++){
                $m3[$i][$j]+=$m1[$i][$k]*$m2[$k][$j];
            }
        }
    }
    return($m3);
}

output:

print_r(matrixmult($array, $array1));

Array ( [0] => Array ( [0] => 10 [1] => 13 ) [1] => Array ( [0] => 20 [1] => 27 ) ) 

source http://sickel.net/blogg/?p=907

Paul
  • 785
  • 2
  • 13
  • 21