I’m writing a matrix multiplication method using java. My class is Table which is a 2D array. This is the constructor of 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;
}
}
}
And this is the method I’m talking about:
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;
}
The method product should return a new Table which is the result of the multiplication of a and b. I think it’s pretty clear what it should do. The problem is that it only computes c[0][0] correctly; So c.get(0,0) is computed correctly, but the results after that are not. Do you see what I’m doing wrong? I appreciate your help.
First thing that looks odd is:
it should be reset in other place too. Hope that helps 🙂