Main Content

Maintain Data Type Compatibility

Define data types for Stateflow® chart data to maintain compatibility between functions and operations. Type conversions prevent run-time errors when charts include different data types.

Data Type Propagation Rules

Stateflow charts handle data type propagation differently based on the action language.

For example, in charts that use MATLAB as the action language, when you add data of type double to data of type int32, the data is type int32. This pattern follows MATLAB typing rules.

In charts that use C as the action language, when you add data of type double to data of type int32, the data is type double. This pattern follows C typing rules.

Type Cast Operations

To convert a value from one data type to another, use the cast operator. You can cast data to an explicit type or to the type of another variable.

Cast to Explicit Data Type

To cast a numeric expression to an explicit data type, use one of these type conversion functions:

  • double

  • single

  • int8

  • int16

  • int32

  • int64

  • uint8

  • uint16

  • uint32

  • uint64

  • boolean

To convert data to fixed-point data types:

  • In charts that use MATLAB as the action language, use the fi (Fixed-Point Designer)

    function.

  • In C action language charts, use the cast function with a fixdt expression.

Override Fixed-Point Data Promotion Rules

In C action language charts, use the := assignment operator to override fixed-point promotion rules.

result := a * b;

This assignment preserves the fixed-point type of the result, and prevents promotion to a wider type that might occur with the standard = operator.

Vector and Matrix Operations

When using vectors and matrices, be aware of indexing differences between MATLAB and C:

  • Charts that use MATLAB as the action language use one-based indexing with parentheses, for example, A(1,2).

  • Charts that use C as the action language use zero-based indexing with square brackets, for example, A[0][1].

This difference affects not only how you access elements but also how you maintain type compatibility when working with arrays.

Data Type Conversions at Interfaces

When data enters or leaves a chart, Simulink® may perform automatic data type conversions. These conversions follow the Stateflow data type conversion rules, which may be different from how Stateflow charts converts data types.

To avoid unexpected type conversions:

  • Use explicit type casting at chart interfaces.

  • Configure the data type conversion settings appropriately. See Data Type Conversion (Embedded Coder).

  • Use the Model Advisor to check for potential data type issues.

Best Practices for Data Type Compatibility

To maintain data type compatibility in your Stateflow charts:

  • Define data types for all inputs, outputs, and local data.

  • Use the same action language throughout your model.

  • Monitor how data types change as they promote through expressions.

See Also

Topics