user990246
user990246

Reputation:

Multiplying two matrices with different dimensions

I am writing an application to multiply matrices. This works nicely as intended for matrices a and b that are nxn:

for(k = 0; k < n; k++) {
    for(i = 0; i < n; i++) {
        tmp = a[i][k];
        for(j = 0; j < n; j++) {
            c[i][j] = c[i][j] + tmp * b[k][j];
        }
    }
}

If a was nxy and b was yxm (implying c to be nxm). How would I modify the above loop to work?

Thanks

Upvotes: 0

Views: 3770

Answers (1)

KCH
KCH

Reputation: 2844

This should work:

for(k = 0; k < y; k++) {
    for(i = 0; i < n; i++) {
        tmp = a[i][k];
        for(j = 0; j < m; j++) {
            c[i][j] = c[i][j] + tmp * b[k][j];
        }
    }
}

Upvotes: 3

Related Questions