# Multiply two 4x4 Matrices

  fn_mat4 fn_multMat4(fn_mat4 a,fn_mat4 b)
{

fn_mat4 ret;

for (j = 0;j < 4;j++)
{

#pragma omp simd
for (i = 0;i < 4;i++)
ret.m[i+j*4]= a.m[j*4]*b.m[i] + a.m[j*4 + 1]*b.m[i+4] + a.m[j*4 + 2]*b.m[i+8] + a.m[j*4 + 3]*b.m[i+12];

}
return ret;
}


If anybody knows how to reduce this to one loop instead of nested loops it would be greatly appreciated.

• Posing compilable code is courteous and makes for a better review. – chux - Reinstate Monica Aug 24 '17 at 18:25

If anybody knows how to reduce this to one loop instead of nested loops it would be greatly appreciated.

2 Alternatives: Unclear if this make for higher performance code for OP.

  for (unsigned j = 0; j < 4; j++) {
unsigned j4 = j * 4;
ret.m[j4 + 0] = a.m[j4]*b.m + a.m[j4 + 1]*b.m[0 + 4] + a.m[j4 + 2]*b.m[0 + 8] + a.m[j4 + 3]*b.m[0 + 12];
ret.m[j4 + 1] = a.m[j4]*b.m + a.m[j4 + 1]*b.m[1 + 4] + a.m[j4 + 2]*b.m[1 + 8] + a.m[j4 + 3]*b.m[1 + 12];
ret.m[j4 + 2] = a.m[j4]*b.m + a.m[j4 + 1]*b.m[2 + 4] + a.m[j4 + 2]*b.m[2 + 8] + a.m[j4 + 3]*b.m[2 + 12];
ret.m[j4 + 3] = a.m[j4]*b.m + a.m[j4 + 1]*b.m[3 + 4] + a.m[j4 + 2]*b.m[3 + 8] + a.m[j4 + 3]*b.m[3 + 12];
}


And

  for (unsigned j = 0; j < 16; j++) {
unsigned i = j % 4;
unsigned j4 = j & 12;  // j4 = j / 4 * 4;
ret.m[j] =
a.m[j4 + 0]*b.m[i + 0] + a.m[j4 + 1]*b.m[i + 4]
+ a.m[j4 + 2]*b.m[i + 8] + a.m[j4 + 3]*b.m[i + 12];
}