简体   繁体   English

将2d数组乘以1d数组

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

I've initialized a 1d and 2d array and now I basically just want to be able to perform matrix multiplication on them. 我已经初始化了一个1d和2d数组,现在我基本上只希望能够对它们执行矩阵乘法。 However, I'm not quite getting the proper answer. 但是,我还没有得到正确的答案。 I think I've mixed up the for loop where I try to ensure I only multiply the correct values, but can't quite get the hang of it. 我认为我混淆了for循环,在这里我尝试确保仅乘以正确的值,但不能完全掌握它。

edit: I've fixed it, I was misunderstanding what the length method of a 2D array returned (thought it returned columns and not rows). 编辑:我已修复它,我误解了2D数组的长度方法返回了什么(认为它返回的是列而不是行)。 The below code is my corrected code. 以下代码是我的更正代码。 Thanks everyone. 感谢大家。

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

There are some problems, first of all, you should decide how the vectors represented, are you multiplying from left or right. 存在一些问题,首先,应确定从左或向右相乘的向量的表示方式。

For the maths: vector 1xn times matrix nxm will result in 1xm , while matrix mxn times nx1 result in mx1 . 对于数学:向量1xn次矩阵nxm将导致1xm ,而矩阵mxnnx1结果mx1

I think the following would work for you: 我认为以下将为您工作:

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

I hope I did not make a mistake, while trying to fix. 我希望我在尝试修复时没有犯错。

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

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