Matrix multiplication in php

孤者浪人 提交于 2020-01-11 13:55:15

问题


Although the order of matrices should be fine, the following code throws back the exception. It might be a tiny thing I'm not being able to notice, but can't figure it out.

<?php
  $mat1 = array(5,1);
  $mat2 = array(1,5);
  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);
  }
  matrixmult($mat1,$mat2);
?>

回答1:


You're specifying your test matrices wrong, in two ways:

  1. The arrays aren't two-dimensional (that is, arrays of arrays of numbers).
  2. Even if you wrapped another array( ) around them, the condition that the width of the first matrix be equal to the height of the second matrix doesn't hold with [5 1] and [1 5], which are both 2 wide and 1 high.

What you need is something like

$mat1 = array(array(5,1));
$mat2 = array(array(1),array(5));



回答2:


Just to round this out. Here is a working solution:

function M_mult($_A,$_B) {
  // AxB outcome is C with A's rows and B'c cols
  $r = count($_A);
  $c = count($_B[0]);
  $in= count($_B); // or $_A[0]. $in is 'inner' count

  if ( $in != count($_A[0]) ) {
    print("ERROR: need to have inner size of matrices match.\n");
    print("     : trying to multiply a ".count($_A)."x".count($_A[0])." by a ".count($_B)."x".count($_B[0])." matrix.\n");
    print("\n");
    exit(1);
  }

  // allocate retval
  $retval = array();
  for($i=0;$i< $r; $i++) { $retval[$i] = array(); }
    // multiplication here
    for($ri=0;$ri<$r;$ri++) {
      for($ci=0;$ci<$c;$ci++) {
        $retval[$ri][$ci] = 0.0;
        for($j=0;$j<$in;$j++) {
          $retval[$ri][$ci] += $_A[$ri][$j] * $_B[$j][$ci];
        }
      }
    }
    return $retval;
  }
}


来源:https://stackoverflow.com/questions/25220655/matrix-multiplication-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!