Matrix Mulitplacation Method

Started by
4 comments, last by GameDev.net 18 years, 10 months ago
Hello, I wrote this matrix multiplacation method in Java. I'm pretty proud of it and I think it is an elegant little solution. I was just wondering if there is a more optimized version of it.

	public static int [] [] MatrixMultiply ( double [] [] A , double [] [] B ){
		
		int y0 = A[0].length;
		int x0 = A.length;
		int y1 = B[0].length;
		int x1 = B.length;
		
		if ( x0 == y1 ){
			int [] [] ProductMatrix = new int [ y0 ] [ x1 ];
			
			for ( int a = 0 ; a < y0 ; a++ ){
				for ( int b = 0 ; b < x1 ; b++ ){
					for ( int c = 0 ; c < y1 ; c++ ){
						ProductMatrix [a] += A[c][a] * B[c];
					}
				}
			}
			return ProductMatrix;
		}
		
		int [] [] InvalidReturn = { { -1 } };
		return InvalidReturn;
		
	}




(0110101101000110)The Murphy Philosophy: Smile . . . tomorrow will be worse.
Advertisement
well if those matrices are fixed sizes you could unroll the loops (does java do this with constants?)
the only oddity i see is storing the result in an integer matrix, but youre consistent about it so i guess its ok.

on the other hand java didnt do implict float->int casts last time i used it, so that code isnt going to compile.
If you're looking for a faster multiplication algorithm, you could take a look at this: Clicky
"What are you trying to tell me? That I can write an O(N^2) recursive solution for a 2-dimensional knapsack?" "No, programmer. I'm trying to tell you that when you're ready, you won't have to." -Adapted from "The Matrix"
As java 1.5 now supports generics, perhaps something like expression templates is now possible on Java too. That would allow you to fuse the loops in more complex expressions (among other things). Altough i'm not sure if generics do provide as much freedom as do templates in C++. Here's a link to the original (?) text on ETs: Expression Templates. And here's another (there's java-stuff also on that site): Angelika Langer: ET.
Well, are you sure the base matrices(?) have the same size all over
(could be that A[0].length!=A[1].length) you got to test for that
(receiveing variables on the stack is "like a box of chocolates" you never know what you are going to get in)

This topic is closed to new replies.

Advertisement