MATLAB: Is there a global setting that makes Stateflow use single precision floats

doubleprecisionsinglestateflowtypecastupcast

There is a controller capable of handling calculations in single precision float format i.e. (real32_T) and not double precision float format i.e. (real_T). There are some transition conditions in the chart where I add two numbers (one of type single and other of type double) and I expect all the calculations should take place in single precision format. So I need a global setting for Stateflow to treat all numbers and variables to be of type single.

Best Answer

The ability to treat all numbers and variables to be of type single by default is not available in Stateflow.
Stateflow treats all numeric constants with decimals as doubles. This is in accordance to the standard C behavior as Stateflow follows C syntax. Hence, both LHS and RHS in the expression should be of type single to avoid type casting. Hence, if we want to treat a decimal value like 3.0 (which is double by default) to be single, it can be done by adding F after the number (eg 0.3F will be considered as single while 0.3 will be taken as double by default). When we add two numbers, one of which is single and other a double, a singlewill upcast itself to be of type double.
Another way is to typecast each number to be of datatype 'single' within flowchart. eg:- single(0.3) will treat the numer 0.3 as single.
Variables can be defined as 'single' in the parameter settings if we want to treat numbers assigned to those variables as single. It can be done as follows:-
1. Open Model Explorer
2. Select the data inside the "Contents" pane
3. Modifying the "DataType" field of one of them
Attached is a test model to demonstrate the same where the numbers 2 and 0.5 are added. Here 0.5 is typecasted as single thereby adding two numbers of type single. On generating the report and looking at testmodel.c file, expressions like typecasts int_T and int32_T during addition of two numbers are no longer visible.
This is the default behaviour of Simulink during simulation and code generation and the functionality to make all the numbers and variables as single by default is currently not available.