Does Setting Variables as Integers for MATLAB Code Generation requires casting every time?
显示 更早的评论
I have a MATLAB project (not Simulink) that I am generating C code for to run on a NVIDIA Jetson Nano. In it, I have a persistent variable that will only be a small integer, but MATLAB coder by default sets it to a double.
To work around this, I explicitly cast the variable to be a be a uint8 using the following snippet:
if isempty(example_var)
example_var=uint8(0);
end
When I then use the Check for Run-Time Issues step in the MATLAB Coder, it fails with the following error
This assignment writes a 'double' value into a 'uint8' type. Code generation does not support changing types through assignment. Check preceding assignments or input type specifications for type mismatches.
I scrolled down to the point where this error was reported, and found that the line in question in the following:
example_var = 0;
This is (obviously) a number that can be represented with a uint8, but MATLAB Coder seems to have decided to use it as a double. If I cast the variable again here, the error goes away. However, my project sets the variable multiple times, and there are many other variables that I would like to represent as an integer. Do I have to manually cast the variable every time that I set it, or is there a way for matlab to automatically convert the number to a uint8?
采纳的回答
更多回答(1 个)
Walter Roberson
2021-3-14
b = uint8(0)
do_something(b)
b(:) = 1
b(:) = do_something_else(b)
3 个评论
Walter Roberson
2021-3-14
Note: this can potentially generate code that creates a double precision 1 and type-converts it to uint8 for the assignment. Compiler optimizers would be permitted to reduce such code down to a single operation, but that would be a Quality of Implementation.
Gabriel Roper
2021-3-14
Walter Roberson
2021-3-14
uint8(0) and other numeric type name conversions with a literal constant are handled at parse time -- for example uint64(20000000000000000001) is not computed as double precision first and then converted. Effectively they become like keywords.
type names with an expression that is not a literal constant are handled at run-time even if they could be handled at compile time. I think... it can be hard to tell.
So when assigning a constant that is not double precision, it is safest and potentially more efficient to put the type name with it instead of relying on indexing to do type conversion.
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB Coder 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!