Documentation Center

  • Trial Software
  • Product Updates

Specify Variable-Size Data Without Dynamic Memory Allocation

Fixing Upper Bounds Errors

If MATLAB® cannot determine or compute the upper bound, you must specify an upper bound. See Specifying Upper Bounds for Variable-Size Data and Diagnosing and Fixing Errors in Detecting Upper Bounds

Specifying Upper Bounds for Variable-Size Data

When to Specify Upper Bounds for Variable-Size Data

When using static allocation on the stack during code generation, MATLAB must be able to determine upper bounds for variable-size data. Specify the upper bounds explicitly for variable-size data from external sources, such as inputs and outputs.

Specifying Upper Bounds for Local Variable-Size Data

When using static allocation, MATLAB uses a sophisticated analysis to calculate the upper bounds of local data at compile time. However, when the analysis fails to detect an upper bound or calculates an upper bound that is not precise enough for your application, you need to specify upper bounds explicitly for local variables.

Constraining the Value of a Variable That Specifies Dimensions of Variable-Size Data.  Use the assert function with relational operators to constrain the value of variables that specify the dimensions of variable-size data. 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 input n to a maximum size of 5, defining L and M as variable-sized matrices with upper bounds of 5 for each dimension.

Specifying the Upper Bounds for All Instances of a Local Variable.  Use the coder.varsize function to specify the upper bounds for all instances of a local variable in a 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];
    Y = [Y Y*u];

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:

  • First dimension is fixed at size 1

  • Second dimension can grow to an upper bound of 10

By default, coder.varsize assumes dimensions of 1 are fixed size. For more information, see the coder.varsize reference page.

Using a Matrix Constructor with Nonconstant Dimensions

You can define a variable-size matrix by using a constructor with nonconstant dimensions. For code in a MATLAB Function block, you must also add an assert statement to provide upper bounds for the dimensions. For example:

function y = var_by_assign(u) %#codegen
assert (u < 20);
if (u > 0)
   y = ones(3,u);
   y = zeros(3,1);
Was this topic helpful?