I am using MATLAB Coder to generate C code which will have to be maintained (as C code), so I am looking for ways to improve the readability of the generated code. Consider the following test function:
function [result] = coder_test(a,b) x = my_mult(a,b); result = my_svd(x);endfunction [ U ] = my_svd( x ) [U,~,~] = svd(x);endfunction [ x ] = my_mult(a,b) x = a*b;end
where coder_test is the entry-point and the dimensions of a and b are 3×4 and 4×3 respectively. The generated code is:
// snip about 650 lines of code defining the 3x3 SVD, called by eml_xgesvd below void coder_test(const double a[12], const double b[12], double result[9]) { double b_a[9]; int i0; int i1; int i2; double unusedU1[9]; double s[3]; for (i0 = 0; i0 < 3; i0++) { for (i1 = 0; i1 < 3; i1++) { b_a[i0 + 3 * i1] = 0.0; for (i2 = 0; i2 < 4; i2++) { b_a[i0 + 3 * i1] += a[i0 + 3 * i2] * b[i2 + (i1 << 2)]; } } } eml_xgesvd(b_a, result, s, unusedU1); }
We can see here that in the generated code, the SVD is moved out of the main function coder_test (and into the function eml_xgesvd), presumably because it is in a separate function in the Matlab code. However, the code to multiply the matrices A and B is still in the function coder_test, even though I moved the multiply into a separate function my_mult in the Matlab code.
To improve readability I would like a way to ensure that in the generated code, the matrix multiply is actually in a separate function. In other words, I would like it to generate something like:
// snip about 650 lines of code defining the 3x3 SVD, called by eml_xgesvd below void my_mult(const double a[12], const double b[12], double x[9]) { for (i0 = 0; i0 < 3; i0++) { for (i1 = 0; i1 < 3; i1++) { b_a[i0 + 3 * i1] = 0.0; for (i2 = 0; i2 < 4; i2++) { b_a[i0 + 3 * i1] += a[i0 + 3 * i2] * b[i2 + (i1 << 2)]; } } } } void coder_test(const double a[12], const double b[12], double result[9]) { double b_a[9]; int i0; int i1; int i2; double unusedU1[9]; double s[3]; my_mult(a,b,b_a); eml_xgesvd(b_a, result, s, unusedU1); }
Is there a way to get MATLAB Coder to do this, or is the only way to do this to manually change the generated code?
Best Answer