note 86164 deleted from function.array-product by googleguy

From: Date: Tue, 22 Oct 2013 08:02:59 +0000
Subject: note 86164 deleted from function.array-product by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-196765@lists.php.net to get a copy of this message
Note Submitter: hdeus at yahoo dot com ---- Here is how you can multiply two arrays in the form of matrixes using a bit of matrix algebra (M*M). By calling the function multiplyMatrix, you will be multiplying two sparse matrixes (zeros need not be included in the array for the operation to be performed). <?php $M = array( 0=>array(1=>1,4=>1), 1=>array(2=>1,3=>1), 3=>array(1=>1), 4=>array(5=>1), 5=>array(6=>1) ); $M1 = multiplyMatrix($M, $M); //multiplying $M by itself echo '<pre>';print_r($M1);echo '</pre>'; function multiplyMatrix($M1, $M2) { #Helena F Deus, Oct 06, 2008 ##Multiply two matrixes; $M1 and $M2 can be sparse matrixes, the indexes on both should match if(is_file($M1)) {$matrix1 = unserialize(file_get_contents($M1));} else $matrix1 = $M1; #transpose M2 $M2t = transpose($M2); foreach ($M2t as $row=>$tmp) { ##sum the result of the value in the col multiplied by the value in the vector on the corresponding row foreach ($M1 as $row1=>$tmp1) { $multiply[$row1] = array_rproduct($tmp,$tmp1); if(!$multiply[$row1]){ exit; } } foreach ($multiply as $row1=>$vals) { $sum[$row][$row1]=array_sum($vals); } } $r=transpose($sum); return ($r); } function transpose($M) { foreach ($M as $row=>$cols) { foreach ($cols as $col=>$value) { if($value) $Mt[$col][$row]=$value; } } ksort($Mt); return ($Mt); } function array_rproduct($a1, $a2) { foreach ($a1 as $line=>$cols) { $a3[$line] = $a1[$line]*$a2[$line]; foreach ($a2 as $line2=>$cols2) { $a3[$line2] = $a1[$line2]*$a2[$line2]; } } ksort($a3); return ($a3); } ?>

« previous php.notes (#196765) next »