# multmatrix()

• 08-17-2006
linuxdude
multmatrix()
I am trying to write a function that multiplies two 4x4 matrices. The only problem is with indexing. In openGL the matrices are oriented like so
Code:

```0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15```
So instead of creating a 2 dimensional array. people create a single array of 16. now when i go to multiply it becomes difficult. I can't seem to come up with a double for loop way to correctly multiply the matrices. Does anyone have any suggestions?
• 08-17-2006
VirtualAce
Code:

```m0 m4 m8 m12 m1 m5 m9 m13 m2 m6 m10 m14 m3 m7 m11 m15```
Depending on the order of the matrix this function varies. However you should be able to get it.

Code:

```for (int i=0;i<4;i++) {   for (int j=0;j<4;j++)   {     for (int k=0;k<4;k++)     {       matOut[i][j]+=mat1[i][k]*mat2[k][j];     }   } }```
Now unroll the inner loops.

matOut[i][j]=(mat1[i][0]*mat2[0][j])+(mat1[i][1]*mat2[1][j]).....

etc, etc.

You can also unroll the j loop with a bit more code.
Now once you unroll it, use the matrix I provided to eliminate all of the loops.
• 08-17-2006
linuxdude
but my array is only a one dimensional array. Every book that I have read has said to keep it this way as to not confuse with c's implementation of 2 dimensional arrays. Should I declare my array otherwise?
• 08-17-2006
Mario F.
It's a strange advise considering matrixes are traditionally 2D containers. Also, from your own experience it becomes harder to code operations on matrixes built from a one dimensional array.

Regardless, if you insist on a 1D array, the solution is to know what are the bounds of each dimension. A 4x4 1D matrix is of size 16, with the second dimension starting at element 8 and ending at element 15

... with the second dimension starting at element 4 and ending at element 7, third starting at 8 and ending at 11, and so forth. Basically the offset of every dimension starting point is 4 indexes
• 08-17-2006
Perspective
Just index as (column + size* row) instead of (size* column + row) in your 1D array
• 08-17-2006
quzah
Code:

```size_t location[] = {     0, 4, 8, 12,     1, 5, 9, 13,     2, 6, 10, 14,     3, 7, 11, 15, }; opengl[ location[ x ] ] = whatever;```
Lookup table.

Quzah.
• 08-17-2006
VirtualAce
That is a 1D array. Check my diagram. I was stating you could do:

m11*m21*.... etc, etc
• 08-17-2006
quzah
Quote:

Originally Posted by Bubba
That is a 1D array. Check my diagram.

Yup.

Quote:

Originally Posted by linuxdude
but my array is only a one dimensional array. Every book that I have read has said to keep it this way as to not confuse with c's implementation of 2 dimensional arrays. Should I declare my array otherwise?

Quzah.
• 08-18-2006
linuxdude
oh ok. I see now. Thanks a lot.