Generate Code for Growing Arrays and Cell Arrays with end + 1 Indexing - MATLAB & Simulink (original) (raw)

Main Content

Code generation supports growing either an array or a cell array in your MATLABĀ® code by using end + 1 indexing. By default, code generation supports variable-size arrays. To verify that this functionality is enabled, use one of these approaches:

Grow Array with (end + 1) Indexing

To grow an array X, you can assign a value to X(end + 1). If you make this assignment in your MATLAB code, the code generator treats the dimension you grow as variable-size.

For example, you can generate code for this code snippet:

... a = [1 2 3 4 5 6]; a(end + 1) = 7;

b = [1 2]; for i = 3:10 b(end + 1) = i; end ...

When you use (end + 1) to grow an array, follow these restrictions:

Growing Variable-Size Column Array That is Initialized as Scalar at Run Time

In MATLAB execution, if you grow a scalar array by using (end+1) indexing, the array grows along the second dimension and produces a row vector. For example, define the function grow:

function z = grow(n, m) n(end+1) = m; z = n; end

Call grow with example inputs:

By contrast, in code generation, suppose that:

In such situations, the generated code attempts to grow the scalar along the first dimension and therefore, produces a run-time error. For example, generate MEX code for grow. Specify the input n to be a :Inf x 1 double array. Specify the input m to be a double scalar.

codegen grow -args {coder.typeof(0, [Inf 1], [1 0]), 1}

Code generation successful.

Run the generated MEX with the same inputs as before.

Attempted to grow a scalar along the first dimension using end+1 indexing. This behavior differs from MATLAB execution which grows a scalar along the second dimension.

How to Avoid This Error. To avoid this error and grow the array along the column dimension in both generated code and MATLAB execution, rewrite your MATLAB code in either of these ways:

Grow Cell Array with {end + 1} Indexing

To grow a cell array X, you can use X{end + 1}. For example:

... X = {1 2}; X{end + 1} = 'a'; ...

When you use {end + 1} to grow a cell array, follow these restrictions: