我正在使用 java 编写矩阵乘法方法。我的类(class)是 Table
,它是一个二维数组。这是 Table
的构造函数:
public Table(int n, int m, int val)
{
assert(n > 0 && m > 0);
elements = new int[n][m];
for(int row = 0; row < elements.length; row++)
{
for(int col = 0; col < elements[row].length; col++)
{
elements[row][col] = val;
}
}
}
这就是我所说的方法:
public static Table product(Table a, Table b)
{
assert(a.numCols() == b.numRows()) : "different dimensions!" + null;
Table c = new Table(a.numRows(), b.numCols(),0);
int res = 0;
for(int row = 0; row < a.numRows(); row++)
{
for(int col = 0; col < b.numCols(); col++)
{
for(int k = 0; k < a.numCols(); k ++)
{
res = res + a.get(row, k) * b.get(k, col);
c.set(row, col, res);
}
}
}
System.out.println(c.toString());
return c;
}
product 方法应该返回一个新的 Table
,它是 a 和 b 相乘的结果。我认为它应该做什么已经很清楚了。问题在于它只能正确计算 c[0][0]
;所以 c.get(0,0)
计算正确,但之后的结果不是。你看到我做错了吗?感谢您的帮助。
最佳答案
首先看起来很奇怪的是:
int res = 0;
它也应该在其他地方重置。希望有所帮助:)
...
for(int col = 0; col < b.numCols(); col++)
{
res = 0;
for(int k = 0; k < a.numCols(); k ++)
....
关于java - 我的矩阵乘法方法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283986/