I'm trying to optimize matrix multiplication implemented using Java with nested loops. I'm planning to use Java 17 vector API to optimize performance.
I have read the documentation of the Vector API, but I am not sure how to apply them to my matrix multiplication code.
I'm using the following code to multiply the metrics based on this tutorial.
int row1 = 4, col1 = 3, row2 = 3, col2 = 4;
int A[][] = { { 1, 1, 1 },
{ 2, 2, 2 },
{ 3, 3, 3 },
{ 4, 4, 4 } };
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 } };
int i, j, k;
// Check if multiplication is Possible
if (row2 != col1) {
System.out.println("Multiplication Not Possible");
return;
}
// Matrix to store the result
// The product matrix will
// be of size row1 x col2
int C[][] = new int[row1][col2];
// Multiply the two matrices
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
My questions are:
- How do I handle cases where the array length or the matrix size is not a multiple of the vector length?
- I would appreciate some guidance or examples on how to use Java 17 vector instructions to optimize matrix multiplication.