Bipin Kafle
Bipin Kafle

Reputation: 129

Matrix multiplication in php

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);
?>

Upvotes: 0

Views: 9144

Answers (3)

ibrahimcalis
ibrahimcalis

Reputation: 1

You must delete the curly braces before return.

<?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);
?>

Upvotes: 0

cwingrav
cwingrav

Reputation: 989

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

Upvotes: 1

Julian
Julian

Reputation: 757

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

Upvotes: 1

Related Questions