Loolooii
Loolooii

Reputation: 9200

What is wrong with my matrix multiplication method?

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.

Upvotes: 1

Views: 546

Answers (4)

Bob Wang
Bob Wang

Reputation: 606

int res = 0; should be between the second and the third for-loops.

Upvotes: 1

Vincent Vanmarsenille
Vincent Vanmarsenille

Reputation: 504

Reset res in the first loop (might need some re-ordering of the loops, havn't checked and matrices is to long ago) or just change

res = res + a.get(row, k) * b.get(k, col);

to

res = c.get(row, col) + a.get(row, k) * b.get(k, col);

Upvotes: 1

msi
msi

Reputation: 2639

First thing that looks odd is:

int res = 0;

it should be reset in other place too. Hope that helps :)

...
        for(int col = 0; col < b.numCols(); col++)
        {
            res = 0;
            for(int k = 0; k < a.numCols(); k ++)
....

Upvotes: 2

Almo
Almo

Reputation: 15871

res is only set to zero all the way outside the whole set of loops. Its value doesn't make a lot of sense in your multiplication core routine. Re-check your loop logic.

Upvotes: 1

Related Questions