Matrix中的矩阵转置

时间:2014-05-24 18:37:36

标签: java matrix transpose

我在Matice类中有一个方法转置。当我在我的m2.matice上应用这个方法时,我可以在调试期间看到我的矩阵正在转置,但是当我打印m2时,我获得与以前相同的矩阵。

    public class Main {
    public static void main(String[] args) {
        Matice m1 = new Matice(5);
        m1.matrixFill(0, 5);
        m1.matrixPrint();

        Matice m2 = new Matice(3);
        m2.matrixFill(-5, 10);
        m2.matrixPrint();

        m2.transpose();
        m2.matrixPrint();
    }
}

package matice;
/**
 *
 * @author Adam Rychter
 */
public class Matice {

    int[][] matice;
    private int n;

    public Matice(int n) {
        this.n = n;
        if(n > 0) {
            matice = new int[n][n];
        }
    }

    public void matrixPrint(){

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.format("%5d", matice[i][j]);                
            }
            System.out.println("");
        }
        System.out.println("");
    }

    public void matrixFill(int a, int b){
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matice[i][j] = (int) (Math.random() * (a + b + 1) - a);                
            }
        }
    }

    public void transpose(){
        int tmp;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                tmp = matice[i][j];
                matice[i][j] = matice[j][i];
                matice[j][i] = tmp;                
            }            
        }
    }
}

4 个答案:

答案 0 :(得分:3)

你的问题是你要将每个元素转置两次!一旦i = row,j = col,一次当i = col,j = row时,具有离开矩阵的净效果。我看到修复它的最简单方法是只在i> j时进行交换(然后测试以确保:)这是一个建议,而不是工作代码:)

答案 1 :(得分:1)

注意j从i到n,而不是1到n;还需要注意两个tmp变量。

  public void transpose(){

    int tmp1, tmp2;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            tmp1 = matice[i][j];
            tmp2 = matice[j][i];
            matice[i][j] = tmp2;
            matice[j][i] = tmp1;
        }
    }

答案 2 :(得分:0)

像这样,也许:

    public void transpose(){
        Matice mL = new Matice(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                mL.matice[i][j] = matice[j][i];
            }
        }
        matice = mL.matice;
   }

请参阅上面的备用,更有效的答案。

答案 3 :(得分:0)

public void transpose(){
    int tmp;
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            tmp = matice[i][j];
            matice[i][j] = matice[j][i];
            matice[j][i] = tmp;                
        }            
    }
}