【发布时间】:2019-03-03 08:38:48
【问题描述】:
这是我的多重方法:
public Matrix mult(Matrix otherMatrix) {
if(!colsEqualsOthersRows(otherMatrix)) // checks if Matrix A has the same number of columns as Matrix B has rows
return null;
int multiplication[][] = new int[rows][columns];
for(int r = 0; r < rows; r++) {
for(int c = 0; c < otherMatrix.columns; c++) {
int sum = 0;
for(int i = 0; i < otherMatrix.columns; i++) {
sum = sum + matrix[r][i]*otherMatrix.matrix[i][c];
multiplication[r][c] = sum;
}
}
}
return new Matrix(multiplication);
}
在驱动程序方法中,每当出现涉及乘法矩阵的问题时,要么是错误的,要么是系统出错。
即
3BC-4BD //which is
B.mult(3).mult(C)).subtract(B.mult(4).mult(D));
这是错误。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at lab1.Matrix. mult(Matrix.java:81) at lab1.Driver. main(Driver.java:128)
这些是我正在使用的矩阵。
Matrix A = new Matrix(new int[][] {{1,-2,3},{1,-1,0}});
Matrix B = new Matrix(new int[][] {{3,4},{5,-1},{1,-1}});
Matrix C = new Matrix(new int[][] {{4,-1,2},{-1,5,1}});
Matrix D = new Matrix(new int[][] {{-1,0,1},{0,2,1}});
Matrix E = new Matrix(new int[][] {{3,4},{-2,3},{0,1}});
Matrix F = new Matrix(new int[][] {{2},{-3}});
Matrix G = new Matrix(new int[][] {{2,-1}});
这是我的Matrix类:
public class Matrix {
int [][] matrix;
int rows, columns;
public Matrix (int[][] m) {
this.matrix = m;
this.rows = m.length;
this.columns = m[0].length;
}
}
我是 JAVA 语言的初学者,请原谅我的无知。请帮忙!
【问题讨论】:
-
当你将不同大小的矩阵相乘时,问题就出现了,如果你从矩阵 B 中取值,你必须检查 B 的大小而不是 C。
-
如何在 mult 方法中解决这个问题?
-
分享你的矩阵码
-
最内层循环的上限应该是列数而不是otherMatrix.columns。此外,请确保在最里面的循环之后分配结果总和,而不是在循环内。
-
@LostSoul:请更新您的问题。通过一些矩阵乘法的教科书示例来检查您的代码。包括测试以确保矩阵操作数实际上与乘法兼容。考虑支持有用的 cmets ;-)