Make matlab use single as standard for code generation
5 views (last 30 days)
How do I tell matlab to use single as standard data type when using embedded coder for simulink, for example in an embedded matlab function?
Right now if i write:
test_struct.var1 = 1;
it uses a double. I could write everywhere:
test_struct.var1 = single(1);
however, this completely clutters up the code. Is there a way to tell the coder to always use singles instead of doubles?
Jonas on 18 Oct 2021
In the 'Configuration Parameters', under the section 'Math and Data Types', choose 'single' for the option 'Default for underspecified data type' instead of 'double'.
Andy Bartlett on 18 Oct 2021
Embedded Coder is designed to keep the generated code consistent with a Simulink model's simulation behavior. Changing doubles to singles only in the generated code is inconsistent with that goal.
To generate code without doubles, it is recommended to change the data types used in the model from double to single.
Single Precision Converter Tool for Simulink
The Single Precision Converter tool automates the conversion process in many causes as shown in this example. The setting that Jonas mentioned is one of several things that are changed by the tool. While running this tool, a Fixed-Point Designer license is required.
Convert from Double MATLAB Code to Single MATLAB Code
If you want to convert a MATLAB file from double to single, you can use this tool. While running this tool Fixed-Point Designer and MATLAB Coder licenses are required.
Authoring Polymorphic Code
If you'd like to author polymorphic code that can be quickly changed from double to single with a simple configuration change consider the types-table and cast-like pattern. This authoring pattern is described in this technical article Best Practices for Converting MATLAB Code. This approach works for singles too, even though the title specifies Fixed Point. If you search that article for 'single' with the quotes, you'll quickly see a types type that includes singles as one of the options.
In addition to using an external types table, there are few key techniques in the approach.
- Use the cast like syntax to control types
- When writing to a variable that has already been typed, preserve the type using indexed assignment. To re-aassign the whole variable but preserve type use colon assignment a(:) = b;
As an author becomes familiar with this pattern, the amount of extra code required for data typing can be minimized.
A benefit of this approach, as opposed to one that only changes things in code generation, is that testing and debugging of the code's behavior in MATLAB, Simulink, and generated code will all be consistent.
Cast-like and indexed assignment are available in base MATLAB.