gpt4 book ai didi

java - 将二维数组乘以一维数组

转载 作者:行者123 更新时间:2023-12-01 13:14:25 26 4
gpt4 key购买 nike

我已经初始化了一个一维和二维数组,现在我基本上只想能够对它们执行矩阵乘法。但是,我还没有得到正确的答案。我想我已经混淆了 for 循环,我试图确保只乘以正确的值,但无法完全掌握它的窍门。

编辑:我已经修复了它,我误解了二维数组的 length 方法返回的内容(认为它返回列而不是行)。下面的代码是我更正后的代码。谢谢大家。

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

最佳答案

这里有一些问题,首先你应该决定 vector 如何表示,是从左乘还是从右乘。

对于数学: vector 1xn乘以矩阵nxm将得到1xm,而矩阵mxn乘以nx1 结果为 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

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

关于java - 将二维数组乘以一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com