开发者

C++ Multiplying 2 ND Matrices

Tricky question, how to multiply 2 ND metrices? of course columnsA == rowsB... Here's what i've got:

void multiply(int *A, int *B, int r1, int c1, int r2, int c2) {
     int sum = 0;
     for (int i=0;i<(c1*r2);i++) {
         for (int j=0;j<c1;j++) {
             sum += A[(i-i%c1)+j] * B[(i%c1)+j*开发者_开发技巧c1];
         }
         cout << sum << " ";
         sum = 0;
    }
}

Calling it:

multiply(&A[0][0],&B[0][0],rowsA,columnsA,rowsB,columnsB);

Works only for rectangular matrices, obviously. Any suggestion? :)


I suggest you use a dedicated library for that, such as Click

Or Click


One more suggestion, to make it error-proof, use below technique:

Write a template wrapper such as,

template<typename TYPE, size_t ROW_A, size_t COL_A, size_t COL_B>
void multiply (TYPE (&A)[ROW_A][COL_A], TYPE (&B)[COL_A][COL_B])
{
  mulitply(&A[0][0], &B[0],[0], ROW_A, COL_A, COL_B, COL_B);
}

There are 2 advantages:

  1. You don't have to pass row/column index manually for both arrays in your code
  2. Error/bug will be caught at compile time if (Column of A != Row of B)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜