MATLAB: How to debug code generated using MATLAB Coder that crashes or gives incorrect results

codecoderdebuggeneratedMATLABmatlab coder

How can I debug code generated using MATLAB Coder that crashes or gives incorrect results?

Best Answer

Note: this distinguishes between MEX function generation (used in MATLAB) and standalone code generation (source code, static library, dynamic library, or executable).
1. Make sure to follow the recommended workflow for generating code using MATLAB Coder:
In particular, make sure to generate and test a MEX function, which contains runtime error checking that may not appear in standalone code.
2. In R2015b and later, runtime error checking can be generated in standalone code using a config object for code generation:
>> cfg = coder.config('lib');
>> cfg.RuntimeChecks = 1;
>> codegen myFunction -config cfg
3. If you are seeing different results from generated code than what you see from MATLAB for the same function, check for the possibility that the generated code is simply using a different (but still correct) implementation of that function. For example, the 'svd' function can output different answers from MATLAB vs generated C code. Note that singular value decomposition is not unique, so a matrix can have multiple decompositions that are all valid.
4. Check that the compiler is supported, as per the following page:
5. Check if there were any warnings during code generation.
6. If generated, ensure that the initialization function is called before the entry-point function, and that the terminate function is called after.
7. Check any calls to external C functions via coder.ceval, ensuring the data type and layout are correct (note that MATLAB uses a column-major layout by default).
8. Try compiling with the debug flag
For MEX, add -g to the codegen command:
>> codegen myFunction -args {1,2} -g
For standalone code generation, create a coder.config object and modify it:
>> cfg = coder.config('dll');
>> cfg.BuildConfiguration = 'Debug';
>> codegen myFunction -config cfg
If (8) resolves the issue, please contact MathWorks Technical Support in order to report this compiler bug.
If none of the above resolve the issue, please contact MathWorks Technical Support.