我尝试使用双数组进行矩阵乘法,但是数组'使用+或* =等运算符既不能添加也不能乘以值。我做错了什么?
import java.util.Arrays;
public class MatrixMultiplication {
public static void main(String[] args) {
//Initializing all required arrays
double[][] matrix1 = new double[][] { { 3.0, 2.0, 1.0 },
{ 1.0, 0.0, 2.0 } };
double[][] matrix2 = new double[][] { { 1.0, 2.0 },
{ 0.0, 1.0 },
{ 4.0, 0.0 }};
double[][] intermediate = new double[][] { { 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0 },
{0.0, 0.0, 0.0}};
double[][] result = new double[][] { { 0.0, 0.0 },
{ 0.0, 0.0 }};
//check arrays' lengths and heights
if ( matrix1.length == matrix2[0].length) {
//multiply first line and first column
for (int i = 0; i == matrix1.length; i++) {
intermediate[i] = matrix1[i] * matrix2[0][i];
result[0] += intermediate[i];
}
//multiply first line and second column
for (int i = 0; i == matrix1.length; i++) {
intermediate[i] = matrix1[i] * matrix2[1][i];
result[1] += intermediate[i];
}
//multiply second line and first column
for (int i = 0; i == matrix1.length; i++) {
intermediate[i] = matrix1[i][1] * matrix2[0][i];
result[0][1] += intermediate[i];
}
//multiply second line and second column
for (int i = 0; i == matrix1.length; i++) {
intermediate[i] = matrix1[i][1] * matrix2[1][i];
result[1][1] += intermediate[i];
}
System.out.println(Arrays.deepToString(result).replace("], ", "]\n"));
} else {
System.out.println("Matrices can not be multiplied"); }
}
}
答案 0 :(得分:1)
问题在于:
//multiply first line and first column
for (int i = 0; i == matrix1.length; i++) {
intermediate[i] = matrix1[i] * matrix2[0][i];
result[0] += intermediate[i];
}
您需要指定一个进行数组乘法的方法。您不能直接将数组的列与标量相乘。您可以手动模仿乘法(将每个元素相乘并添加它们,然后将其放入正确的索引中)。