Why do I need to specify the datatype when I assign a variable in Embedded MATLAB block in Simulink 6.3 (R14SP3)?

9 views (last 30 days)
I am using an Embedded MATLAB block in Simulink 6.3 (R14SP3). I have defined an expression:
m = int16(1);
m = 10;
When I run the model Simulink returns the following error message:
Class mismatch (int16 ~= double). The class to the left is the class of the left-hand side of the assignment.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This is expected behavior for the Embedded MATLAB Function Block.
In Embedded MATLAB once a variable is initialized its size and type may not be changed. Since the default type for a scalar is double the code
m = int16(1);
m = 10;
will error out because 10 is of type double and m is of type int16.
You can recast values for variable assignment in two ways.
1) Explicitly recast the value with the appropriate typcast function:
m = int16(1);
m = int16(10);
2) Implicitly recast the value using the colon operator:
m = int16(1);
m(:) = 10;
For more information on variable initialization and assignment in Embedded MATLAB Function Blocks see the documentation section titled: "Embedded MATLAB Coding Style", or you can execute the following in an MATLAB R2008a command window:
web([docroot '/toolbox/eml/ug/brdqvz_.html#bq2l74g']);

More Answers (1)

William Katzianer
William Katzianer on 10 Jan 2019
This is a huge flaw. Code generation for C code, is almost always, targeted for integer manipulation. Why is it that Simulink would attempt to produce doubles when it is very clear that the developer wants integers?
I'm working on this same exact problem, and my work around is creating a persistent variable ONE that equals uint16(1), and persistent variable ZERO that equals uint16(0).
In order to avoid unecessary casting operations, you have to create these extra variables.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!