2013-04-11 51 views
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"); 
    } 

} 
} 

感谢您的帮助。

回答

1

这可能会遍历2D数组并打印每个元素。

static final int ROWS = 2; 
static final int COLS = 4; 

int[][] a2 = new int[ROWS][COLS]; 

//... Print array in rectangular form 
for (int i = 0; i < ROWS; i++) { 
    for (int j = 0; j < COLS; j++) { 
     System.out.print(" " + a2[i][j]); 
    } 

    System.out.println(""); 
} 
+1

我喜欢你的指数选择http://stackoverflow.com/questions/7395556/why-does-the-order-of-loops-in-a-matrix-multiply-algorithm-affect-performance – 2013-04-11 02:06:12