Advertisement

matrix multiplication algorithm - this doesn't work!

Started by December 12, 2002 10:41 AM
2 comments, last by DyDx 22 years, 2 months ago
I wrote this matrix multiplication code a few months ago, and I thought it worked, but now I''m seeing that in a 2x2 * 2x12 case, it isn''t working! Here is the code:

Matrix Matrix::operator*(const Matrix &A)
{
     int x;
     int y;
     int k;
     float temp;
     Matrix C(a, A.b);


     for (x = 0; x < A.a; x++)
         for (y = 0; y < b; y++)
         {
           temp = 0;
           for (k = 0; k < A.b; k++)
              temp += A.Array[k][y] * Array[x][k];
           C.Array[x][y] = temp;
         }
     return C;

} 
a is the number of rows in the first matrix and A.b is the number of columns in the second matrix. Can someone find what is wrong with this? Sorry if this has been asked before, but the search function is down. Thanks!
You take your loop endponts from the wrong matrixes. Switch.
Advertisement
I''m not sure I understand what you mean...
All of your loop ending values are wrong. x should vary fom 0 to a, not A.a (since the number of rows of your destination matrix are defined by "this" and not A.) y should range from 0 to A.b, since the number of columns comes from A not "this". k should range from 0 to b, or from 0 to A.a, since A.a must equal b.

Therefore,

for (x = 0; x < a; x++)     // correction  for (y = 0; y < A.b; y++) // correction  {    temp = 0;    for (k = 0; k < b; k++) // correction      temp += A.Array[k][y] * Array[x][k];    C.Array[x][y] = temp;  } 


By the way, I would recommend changing your notation. "a", and "b" are not at all intuitive variable names. Why not use something like "numrows" and "numcolumns". Doesn''t cost you anything in terms of performance since its just source code, and the code will be much more intuitive, in my opinion.


Graham Rhodes
Senior Scientist
Applied Research Associates, Inc.
Graham Rhodes Moderator, Math & Physics forum @ gamedev.net

This topic is closed to new replies.

Advertisement