Specify Upper Bounds for Variable-Size Arrays - MATLAB & Simulink (original) (raw)
Main Content
Specify upper bounds for an array when:
- Dynamic memory allocation is disabled.
If dynamic memory allocation is disabled, you must specify upper bounds for all arrays. - You do not want the code generator to use dynamic memory allocation for the array.
Specify upper bounds that result in an array size (in bytes) that is less than the dynamic memory allocation threshold.
Specify Upper Bounds for Variable-Size Inputs
If you generate code by using codegen
, to specify upper bounds for variable-size inputs, use thecoder.typeof
construct with the -args
option. For example:
codegen foo -args {coder.typeof(double(0),[3 100],1)}
This command specifies that the input to function foo
is a matrix of real doubles with two variable dimensions. The upper bound for the first dimension is 3. The upper bound for the second dimension is 100.
If you generate code by using the MATLAB® Coder™ app, see Define Types of Entry-Point Inputs by Using the MATLAB Coder App.
Specify Upper Bounds for Local Variables
When using static allocation, the code generator uses a sophisticated analysis to calculate the upper bounds of local data. However, when the analysis fails to detect an upper bound or calculates an upper bound that is not precise enough for your application, you must specify upper bounds explicitly for local variables.
Constrain the Value of Variables That Specify the Dimensions of Variable-Size Arrays
To constrain the value of variables that specify the dimensions of variable-size arrays, use the assert
function with relational operators. For example:
function y = dim_need_bound(n) %#codegen assert (n <= 5); L= ones(n,n); M = zeros(n,n); M = [L; M]; y = M;
This assert
statement constrains inputn
to a maximum size of 5. L
is variable-size with upper bounds of 5 in each dimension. M
is variable-size with an upper bound of 10 in the first dimension and 5 in the second dimension.
Specify the Upper Bounds for All Instances of a Local Variable
To specify the upper bounds for all instances of a local variable in a function, use thecoder.varsize
function. For example:
function Y = example_bounds1(u) %#codegen Y = [1 2 3 4 5]; coder.varsize('Y',[1 10]); if (u > 0) Y = [Y Y+u]; else Y = [Y Y*u]; end
The second argument of coder.varsize
specifies the upper bound for each instance of the variable specified in the first argument. In this example, the argument [1 10]
indicates that for every instance of Y
:
- The first dimension is fixed at size 1.
- The second dimension can grow to an upper bound of 10.