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){
	if(count($m1[0])!=$p){throw new Exception('Incompatible matrixes');}
	for ($i=0;$i< $r;$i++){

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){
	for($i=0;$i< $r;$i++){

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.