0
我的目標是在兩個數組相乘時打印出矩陣。我在做什麼錯誤的代碼?我如何得到它以便打印矩陣? (對不起,我不知道我應該提供什麼其他細節,除非增加更多細節,否則我不能提交這篇文章)。在java中乘以二維數組(矩陣)
public class Matrices {
static int mRows = 0;
static int mCol = 0;
static int nRows = 0;
static int nCol = 0;
public static int[][] multiplyMatrices(int[][] m, int[][] n){
mRows = m.length;
mCol = m[0].length;
nRows = n.length;
nCol = n[0].length;
if(canBeMultiplied(m,n) == false){
throw new IllegalArgumentException("Cannot multiply arrays");
}
int[][] answer = new int[mRows][nCol];
for(int i = 0; i < mRows; i++){
for(int j = 0; j < nCol; j++){
for(int k = 0; k < mCol; k++){
answer[i][j] += m[i][k] * n[k][j];
}
}
}
return answer;
}
public static boolean canBeMultiplied(int[][] m, int[][]n){
mRows = m.length;
mCol = m[0].length;
nRows = n.length;
nCol = n[0].length;
if(nRows == mCol){
return true;
}
return false;
}
public static void main(String[] args) {
int[][] temp1 = {{1,2,3},{4,5,6}};
int[][] temp2 ={{1},{2},{3}};
for(int i = 0; i < mRows; i++){
for(int j = 0; j < nCol; j++){
System.out.print(multiplyMatrices(temp1,temp2)[i][j]);
}
System.out.print("\n");
}
}
}
感謝您的幫助。
我喜歡你的指數選擇http://stackoverflow.com/questions/7395556/why-does-the-order-of-loops-in-a-matrix-multiply-algorithm-affect-performance – 2013-04-11 02:06:12