PHP Matrix multiplication

Needing to do some matrix multiplication in php, I found some code that looked quite promising, but it had a couple of problems: In addition to the matrixes, it needed the max dimentions of the matrixes as arguments and it returned a matrix with these max dimentions, eg, I needed to multiply a 4×4 with a 1×4 matrix and got the answer as a 4×4 matrix, although if I ignored all the zeros, the anwer was correct, I didn’t want to use that code, so go on:

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

It could have been made a bit more robust by adding some checks if all the subarrays were the same size, but I have so far not bothered to do that.

And in addition, I'll throw in a matrix transposer for free:

function matrixtransp($m){
	$r=count($m);
	$c=count($m[0]);
	$mt=array();
	for($i=0;$i< $r;$i++){
		for($j=0;$j<$c;$j++){
			$mt[$j][$i]=$m[$i][$j];
		}
	}
	return($mt);
}

Again, I could do some checks to see that the matrix really is a matrix and not a random collection of arrays, but not now.

Quite simple code, but I have not been able to find anything that works well anywhere.

This entry was posted in php. Bookmark the permalink.