Matrix multiplication in php

前端 未结 3 1575
难免孤独
难免孤独 2021-01-26 17:29

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.

3条回答
  •  无人共我
    2021-01-26 17:51

    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;
      }
    }
    

提交回复
热议问题