繁体   English   中英

将2d数组乘以1d数组

[英]multiply a 2d array by a 1d array

我已经初始化了一个1d和2d数组,现在我基本上只希望能够对它们执行矩阵乘法。 但是,我还没有得到正确的答案。 我认为我混淆了for循环,在这里我尝试确保仅乘以正确的值,但不能完全掌握它。

编辑:我已修复它,我误解了2D数组的长度方法返回了什么(认为它返回的是列而不是行)。 以下代码是我的更正代码。 感谢大家。

public static double[] getOutputArray(double[] array1D, double[][] array2D) {
    int oneDLength = array1D.length;
    int twoDLength = array2D[0].length;
    double[] newArray = new double[array2D[0].length]; // create the array that will contain the result of the array multiplication  
    for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
        double c = 0;
        for (int j = 0; j < oneDLength; j++) {
            double l = array1D[j];
            double m = array2D[j][i];
            c += l * m; // sum the products of each set of elements
        }
        newArray[i] = c;
    }
    return newArray; // pass newArray to the main method
} // end of getOutputArray method

存在一些问题,首先,应确定从左或向右相乘的向量的表示方式。

对于数学:向量1xn次矩阵nxm将导致1xm ,而矩阵mxnnx1结果mx1

我认为以下将为您工作:

public static double[] getOutputArray(double[] array1D, double[][] array2D) {
  int oneDLength = array1D.length;
  int twoDLength = array2D.length;
  double[] newArray = new double[twoDLength]; // create the array that will contain the result of the array multiplication
  assert twoDLength >0 && array2D[0].length == oneDLength;
  for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
      double c = 0;
      for (int j = 0; j < oneDLength; j++) {
          double l = array1D[j];
          double m = array2D[i][j];
          c += l * m; // sum the products of each set of elements
      }
      newArray[i] = c;
   }
   return newArray; // pass newArray to the main method
} // end of getOutputArray method

我希望我在尝试修复时没有犯错。

暂无
暂无

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

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