This topic is now archived and is closed to further replies.


Lame question about matrices

Recommended Posts

gameovercl    122
Hi there! I have to multiply two 4x4 matrices stored as an 1D array of 16 floats. I know that OpenGL has functions to multiply matrices, but I would like to see some code to do this task... So, if you know how to do it, please post the code here By the way... remember that OpenGL uses column-major matrices (anyway, I''m using an array such as GLfloat matrix[16]; ) Thanks in advance! Cristián Ramírez (gameovercl) ICQ #38991565 Viña del Mar CHILE

Share this post

Link to post
Share on other sites
Ben_    122

it was just a quick think, but it should be right.
If you use a column major Matrix use:

int i,j,k;
GLfloat[16] m1, m2; // the matrices to multiply
GLfloat[16] resultMatrix={0} // initialize everything with 0
for (i=0; i<4;++1)
for (j=0; j<16; j+=4)
for (k=0; k<4; ++k)
resultMatrix[i+j] += m1[i+k*4]*m2[j+k];

It is easy to generalize it to any matrix multiplication.
Remember that this is not optimized (e.g. <<2 would be faster as *4 but that should be recognized by the compiler). So whenever possible use the prebuild OpenGL functions, or matrics multiplication of optimized math libs.

Greetings Ben

Share this post

Link to post
Share on other sites
Dragonus    122
I won''t implement it code-wise, but it''s easier to see it this way.

Say you have two matrices of size n-by-n, as such:

[A(1,1) A(1,2) ... A(1,n)] [B(1,1) B(1,2) ... B(1,n)]
[A(2,1) A(2,2) ... A(2,n)] * [B(2,1) B(2,2) ... B(2,n)]
[ ... ... ... ... ] [ ... ... ... ... ]
[A(n,1) A(n,2) ... A(n,n)] [B(n,1) B(n,2) ... B(n,n)]

The product of these two matrices will also be an n-by-n matrix (let''s call it R) where the value the value each cell (i,j) (for i and j integers between 1 and n) is given by the following property:

R(i,j) = A(i,1)*B(1,j) + A(i,2)*B(2,j) + A(i,3)*B(3,j) + ... + A(i,n)*B(n,j)

If you know anything about dot products of vectors, it''s just like calculating the dot product of A''s ith row and B''s jth column.

Now granted, I used double-indeces on mine and didn''t use the number 0 for ease of use. So yours will look something like Ben''s up yonder. However, this is the theory behind the code.

~ Dragonus

Share this post

Link to post
Share on other sites
Eeatha    122
If you are coding it (I.E. the X86 processor is going to be doing the calculations) then it will be faster to use double indecies. In memorey they are stored as a single column, and the forumlae so faithfully typed out above would be done in realtime using a pipeline that calculates memorey offsets on X86 archietectures, instead of using the ALU and waiting for two cycles to complete the addition and multiplication for you.

Share this post

Link to post
Share on other sites