简体   繁体   English

Java乘法矩阵

[英]Multiplying matrices Java

I've been have some problems multiplying the matrices for this code, when I do it by hand and with a calculation tool I get something completely different than what my code is giving me. 我在乘以该代码的矩阵时遇到了一些问题,当我手动使用计算工具进行操作时,我得到的东西与我的代码给我的完全不同。

Code: 码:

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();
        }
    }
}

Results: 结果:

 ---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

I don't quite see where I'm messing up the equation 我不太明白我在哪里弄糟

Well the first thing I would do is 0-initialise colaC since you're using += on its entries. 好吧,我要做的第一件事是0初始化colaC因为您在其条目上使用+= The way you're doing it now can't lead to the correct result. 您现在的操作方式无法获得正确的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM