简体   繁体   English

如何在Java中仅用一个循环将两个矩阵相乘?

[英]How to multiply two matrices with only one loop in Java?

This is the traditional method I've found using 3 "for" loops. 这是我使用3个“ for”循环发现的传统方法。

    public int [][] multiMatrices(int[][] m1, int [][] m2){

    int fil_m1 = m1.length;
    int col_m1 = m1[0].length;

//  int fil_m2 = m2.length;     //NOT NECESSARY
    int col_m2 = m2[0].length;

    int [][] end = new int [fil_m1][col_m2];

    for (int x=0; x < end.length; x++) {
         for (int y=0; y < end[x].length; y++) {
            for (int z=0; z<col_m1; z++) {
              end[x][y] += m1[x][z]*m2[z][y]; 
            }
         }
    }
    return end;
}

I am now trying to obtain the same result, but the goal is to use only one "for". 我现在正在尝试获得相同的结果,但目标是仅使用一个“ for”。 For the sake of the exercise I can't use any external library. 为了练习,我不能使用任何外部库。 I've found something called the Strassen algorithm, it may or may not help. 我发现了一种叫做Strassen算法的东西,它可能有帮助,也可能没有帮助。

Any help would be much appreciated. 任何帮助将非常感激。

 for (int x=0,y=0,z=0; x < end.length ; z++) {

              if(z==col_m1) {z=0;y++;}                
              if(y==end[x].length){y=0;x++;}
              end[x][y] += m1[x][z]*m2[z][y]; 
         }
    }

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

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