Back to the old Java Grid Stone this week, but hey, it’s fun anyway. This time, it’s Matrix Multiplication. I failed to find sufficiently explained information about this horrid excuse for Java, so I want to help everyone else out.
In java, you’re typically dealing with matrices of int or double. The code I provide below can handle doubles just fine, just exchange the two and that should do it.
I dare you to try out some paper matrix multiplication. Getting a feel for it is a great idea. But basically, without doing anything too scary, just remember Rows then Columns. As my textbook explained, RC Cola.
We assume that our two parameters are a and b, both arrays of arrays of ints, properly formed to be multiplied.
First, you need figure out how to get
- The first matrix’s number of rows:
int aRows = a.length - The first matrix’s number of columns:
int aColumns = a[0].length - The second matrix’s number of rows:
int bRows = b.length - The second matrix’s number of columns:
int bRows = b[0].length
As you may already know, the result of two matrices that can be multiplied is dependent on the two parent matrices rows and columns.
In fact, this is shown by int[][] resultant = int[aRows][bColumns];. All pretty standard so far.
The explanation for the following nest of for loops gets cloudy.
for(int i = 0; i < aRows; i++): this loop controls the row positionfor(int j = 0; j < bColumns; j++): this loop controls the column positionfor(int k = 0; k < aColumns; k++): controls the index of which individual cell is being multiplied and added up
It's a nasty mess. I present to you now, my code, as is.
public static int[][] multiply(int a[][], int b[][]) {
// Remember RC, Row-Column.
int aRows = a.length, aColumns = a[0].length, bRows = b.length, bColumns = b[0].length;
if ( aColumns != bRows ) {
throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
}
int[][] resultant = new int[aRows][bColumns];
for(int i = 0; i < aRows; i++) { // aRow
for(int j = 0; j < bColumns; j++) { // bColumn
for(int k = 0; k < aColumns; k++) { // aColumn
resultant[i][j] += a[i][k] * b[k][j];
}
}
}
return resultant;
}
I hope my simple explainations can help someone, since this certainly a convoluted thing by any stretch of the imagination.
Happy multiplying!
Possibly related posts: