乘以矩阵Java

时间:2015-01-28 21:36:09

标签: java arrays matrix multiplying

我在使用这些代码的矩阵时遇到了一些问题,当我手工完成并使用计算工具时,我得到的东西与我的代码给出的东西完全不同。

代码:

public class mult1 {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double[][] colaO = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//orginal
        double[][] colaD = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//copy
        double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
        mult1 test = new mult1();
        test.output(colaC);
        test.Alg1(colaO, colaD, colaC);
        test.output(colaC);
    }
    public void Alg1(double colaO[][],double colaD[][],double colaC[][]){
        for(int i=0;i<colaO.length;i++){
            for(int j=0;j<colaO.length;j++){
                for(int k=0;k<colaO.length;k++){
                    colaC[i][j]+=colaO[i][k]*colaD[k][j];
                }
            }
        }
    }
    public void output(double colaC[][]){
        for(int i=0;i<colaC.length;i++){
            for(int j=0;j<colaC.length;j++){
                System.out.printf("%.3f",colaC[i][j]);
                System.out.print(" ");
            }
            System.out.println();
        }
    }
}

结果:

 ---original-----
 0.900 0.050 0.050 
 0.050 0.900 0.050 
 0.050 0.050 0.900 
 ---what i'm getting------
 1.715 0.143 0.143 
 0.143 1.715 0.143 
 0.143 0.143 1.715 
 ---should be-----
 0.815 0.092 0.092
 0.092 0.815 0.092
 0.092 0.092 0.815

我不太清楚我在搞乱这个等式的地方

2 个答案:

答案 0 :(得分:1)

我要做的第一件事是0-initialise colaC,因为你在其条目上使用+=。你现在这样做的方式无法获得正确的结果。

答案 1 :(得分:0)

double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs

应该是

double[][] colaC = {{0,0,0},{0,0,0},{0,0,0}};//for algs