Java中的数学运算符用于矩阵乘法

时间:2014-04-03 04:43:31

标签: java

您好我是Java编码的新手,所以请原谅任何愚蠢的错误或问题。我从一些互联网资源获得了这个代码,它将两个矩阵相乘,并用Java生成结果。我已编辑它供我自己使用。代码如下:

 for ( c = 0 ; c < 3 ; c++ )
         {
            for ( d = 0 ; d < 1 ; d++ )
            {   
               for ( int k = 0 ; k < 3 ; k++ )
               {
                  Math.sum = sum + transformation[c][k]*sub[k][d];
               }

               multiply[c][d] = sum;
               sum = 0;
            }
         }

         System.out.println("Product of entered matrices:-");

         for ( c = 0 ; c < 3 ; c++ )
         {
            for ( d = 0 ; d < 1 ; d++ )
               System.out.print(multiply[c][d]+"\t");

            System.out.print("\n");
         }

所以现在我总是得到红线并且乘以说&#39;总和无法解决或者不是一个字段&#39;和&#39;乘法无法解析为变量&#39;。任何人都可以请解释错误的原因以及如何解决。感谢

3 个答案:

答案 0 :(得分:1)

public class Multiply {

public static void main(String[] args) {
    int rows=3, columns=3;
    double multiply[][] = new double[rows][columns]; // product of transformation X sub
    double matA[][] = { { 2, 3, 6 }, { 1, 4, 6 }, { 4, 1, 3 } },
       matB[][] =  { { 2, 1, 0 }, { 3, 5, 1 }, { 3, 2, 1 } }, 
       sum;

    for (int k = 0; k < columns; k++) {
        for (int c = 0; c < rows; c++) {
            sum = 0;
            for (int d = 0; d < columns; d++) {
                sum = sum + matA[c][d] * matB[d][k];
            }
            multiply[c][k] = sum;
        }
    }
    System.out.println("Product of Matrix A & B matrices:-");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++)
            System.out.print(multiply[i][j] + "\t");
        System.out.print("\n");
    }
}

}

答案 1 :(得分:0)

你需要这个:

    int multiply[][] = new int[somesize][somesize] ;
    for ( c = 0 ; c < 3 ; c++ )
    {
           for ( d = 0 ; d < 1 ; d++ )
           {   int sum = 0; // Creating local variable 'sum'
                  for ( int k = 0 ; k < 3 ; k++ )
                  {
                        sum = sum + transformation[c][k]*sub[k][d];
                  }

                  multiply[c][d] = sum;

            }


     }

答案 2 :(得分:0)

我真的只是你采用数学库总和方法并将其设置为一个值;该方法应该返回一个值Sum = Math.sum(5,4)