Kalina
Kalina

Reputation: 5594

How to multiply two 4x4 matrices, written as two 16-element arrays?

I need to have a 4x4 matrix like this:

1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

represented as an array like this:

[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]

How do I multiply two such "matrices"? I've been struggling with how to make the work for a few days now. I'm thinking this would require three for loops? Maybe two? Would they go to 4 or 16? Some pseudocode would be greatly appreciated :(

Upvotes: 1

Views: 2589

Answers (1)

Kalina
Kalina

Reputation: 5594

I think I did it!

result = A*B:

for(var k=0; k<=12; k+=4){
    for(var i=0; i<4; i++){
        for (var j=0, bCount=0; j<4; j++, bCount+=4){
            result[k+i] += A[k+j%4] * B[bCount+i%4];
        }
    }
}

Upvotes: 4

Related Questions