Does it matter how the nested loop is ordered in a print method ( for example when multiplying matrices)..It seems that when I change the order of the for statements in the print method below, the multiplication is incorrect ( the resultant matrix is incorrect) ...Anyone have any idea? Maybe I have an error in my code??
class Q2Code{
static final int row1 = 6;
static final int col1 = 6;
static final int row2 = 6;
static final int col2 = 6;
public static void main (String args[]){
int m1[][] = new int [row1][col1];
int m2[][]= new int [row2][col2];
int result[][]= new int [row1][col2];
build(m1);
build(m2);
multiply(m1,m2,result);
printMatrix(m1);
System.out.println();
printMatrix(m2);
System.out.println();
printMatrix(result);
}
// Create a new method - build - to initialise a matrix in a random manner
static void build(int m1[][]){
for(int j=0;j<m1.length;j++){
for(int k=0; k<m1[0].length;k++){
m1[j][k]=(int)(Math.random()*100)%5;
}
}
}
// Create a new method - multiply - to define how the resultant matrix will be calculated
static void multiply(int m1[][],int m2[][],int res[][]){
for(int k=0; k<res[0].length;k++){
for(int j=0;j<res.length;j++){
res[j][k] = product(m1,m2,j,k);
}
}
}
// Create a new method - product - that will specify how the operation of the multiplication will take place
static int product(int m1[][],int m2[][], int row, int col){
int sum=0;
//Multiply rows in matrix 1 into columns of matrix 2
for(int j=0;j<m2.length;j++){ //Note the useful guard as columns in matrix 1 must equal rows in matrix 2
sum = sum + m1[row][j]* m2[j][col];
}
return sum;
}
// Create a new method - printMatrix - which defines how a matrix will be printed
static void printMatrix(int m1[][]){
for (int j=0; j<m1.length; j++){
for (int k=0; k<m1[0].length;k++){
System.out.printf("%4d",m1[j][k]);
}
System.out.println();
}
}
}