I was doing the class tutorial to have matrix multiplication from two dimensional arrays: X (3x2) and Y (2x3).
package t7;
public class Q5
{
public static void main(String[] args)
{
int[][] matrix_X = new int [3][2];
int[][] matrix_Y = new int [2][3];
int[][] result = new int [3][3];
for (int i=0; i<matrix_X.length; i++)
{
for(int j=0; j<matrix_X[i].length; j++)
{
matrix_X[i][j] = (int)(Math.random() * 100);
matrix_Y[i][j] = (int)(Math.random() * 100);
}
}
System.out.println("Matrix X is:");
printMatrix(matrix_X);
System.out.println("Matrix Y is:");
printMatrix(matrix_Y);
result = multiplyMatrix(matrix_X, matrix_Y);
}
public static void printMatrix(int[][] m)
{
for (int i=0; i<m.length; i++)
{
for (int j=0; j<m[i].length; j++)
{
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public static int[][] multiplyMatrix(int[][] x, int[][] y)
{
int rows_X = x.length;
int col_X = x[0].length;
int col_Y = y[0].length;
int[][] temp = new int[rows_X][col_Y];
for (int i=0; i<rows_X; i++)
{
for (int j=0; j<col_Y; j++)
{
for (int k=0; k<col_X; k++)
{
temp[i][j] = temp[i][j] + x[i][k] * y[k][j];
}
}
}
return temp;
}
}
The problem is always array index out of bounds expection.