I have some Matlab m-code that involves matrix operations, which I had to convert to C code. I’ve reviewed my code’s logic numerous times, and can’t yet find the logical flaw that’s preventing my C code from matching my m-file’s values.

Here’s a description of the code, and of the bug:

~ the Matlab code multiplies the output of the call to trans_axis() (output = 4x4 matrix of doubles), by the goalTM matrix, which is also 4x4. The result is the updated value for the 4x4 goalTM matrix.

~ my C code seeks to reproduce the Matlab functionality. Since I didn’t think that it would be a good idea to call

MatrixMult(goalTM, TM1, goalTM);

… because it might result in overwriting the goalTM values that are the inputs to the function, I instead use a temporary 4x4 double array named out1[][], into which the MatrixMult() function’s outputs are copied. I then copy the out1[][] values back into the goalTM[][] array, before the for loop executes again.

Here’s the original m-code:

Code:

for j=1:5
goalTM=goalTM*trans_axis(rotaxis(j,1),goal_angles(j),translation(j,1));
end

My C code:

Code:

for(j = 0; j < 5; j++){
/* call trans_axis() function, which writes output values into the TM1 array */
/* note: I have confirmed that trans_axis() is working properly and passes back the correct TM1 output matrix */
trans_axis(rotaxis[j][0],goal_angles[j],translation[j][0],TM1);
/* multiply the current goalTM[4][4] matrix by the TM1[4][4] matrix, and return out1[4][4] matrix */
MatrixMult(goalTM, TM1, out1);
/* PROBLEM: the *first* out1[4][4] value is correct (showing that the MatrixMult() function is working properly), but the 2^{nd} and subsequent out1 matrices' values are incorrect, indicating some mismanagement of the variables. */
/* copy the output matrices back into the goalTM array */
for(a = 0; a < 4; a++){
for(b = 0; b < 4; b++){
goalTM[a][b] = out1[a][b];
}
}
} /* end for(j…) loop */

Can anyone spot the logical flaw in my translation of Matlab code into C code? To restate the bug/problem, I get the correct result from the *first* call to MatrixMult(), but then the out1[][] output of the *second*, and all subsequent, calls to MatrixMult() are incorrect. Thanks in advance for your insights.