我已经初始化了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
答案 0 :(得分:1)
存在一些问题,首先,你应该决定向量的表示方式,你是左右相乘。
对于数学:向量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
我希望在尝试修复时我没有犯错。