MATLAB: Am I getting a computed maximum size is not bounded error in a MATLAB function block in Simulink R2018b

blockboundedcomputedfunctionmaximumsimulinksimulink codersize;tunable

Best Answer

The reason for the error is that there is a dynamically sized array in the MATLAB Function Block that depends on a tunable input parameter. In the example the array "B" is equal to "ones(A)" where "A" is a tunable input parameter. Because "A" is unknown at compile-time, the size of "B" is also unknown at compile-time and thus we cannot statically allocate memory for "B". Even if we define a max size for "B" using "coder.varsize", there is no guarantee that "A" will be less than the maximum size for B, thus the error persists.
Here are three possible solutions to this problem:
1. If you do not need the parameter "A" to be tunable, then you can make "A" nontunable by un-checking the "Tunable" checkbox for A in the "Ports and Data Manager" (link below). Now we can check for the size of B at compile-time and the error is removed.
2. You can also add an "assert" statement that can be used to enforce the max size of "B" and thus the B will be statically allocated at its maximum size. For example, add the following line to the MATLAB Function block code:
assert(A<10);
3. We can specify the variable sized arrays to be dynamically allocated, thus we do not need to know their size at compile-time because they will be set at run-time. We can do this by turning on "Dynamic Memory Allocation in MATLAB Functions" in the configuration parameters. Also by setting the "Dynamic Memory Allocation Threshold in MATLAB Functions" to "0", we can guarantee that all variable sized arrays will be dynamically allocated. See link for details: