Control Whether a Cell Array Is Variable-Size

The code generator classifies a variable-size cell array as homogeneous. The cell array elements must have the same class. In the generated code, the cell array is represented as an array.

If a cell array is an entry-point function input, to make it variable-size:

• At the command line, you can use the coder.typeof function or the coder.newtype function to create a type for a variable-size cell array. For example, to create a type for a cell array whose first dimension is fixed and whose second dimension has an upper bound of 10, use this code:

t = coder.typeof({1 2 3}, [1 10], [0 1])

• In the MATLAB® Coder™ app, select Homogeneous cell array as the type of the input. For the variable-size dimension, specify that it is unbounded or has an upper bound.

If a cell array is not an entry-point function input, to make it variable-size:

• Create the cell array by using the cell function. For example:

function z = mycell(n, j)
%#codegen
x = cell(1,n);
for i = 1:n
x{i} = i;
end
z = x{j};
end

For code generation, when you create a variable-size cell array by using cell, you must adhere to certain restrictions. See Definition of Variable-Size Cell Array by Using cell.

• Grow the cell array. For example:

function z = mycell(n)
%#codegen
c = {1 2 3};
for i = 1:n
c{end + 1} = 1;
end
z = c{n};
end

• Force the cell array to be variable-size by using coder.varsize. Consider this code:

function y =  mycellfun()
%#codegen
c = {1 2 3};
coder.varsize('c', [1 10]);
y = c;
end

Without coder.varsize, c is fixed-size with dimensions 1-by-3. With coder.varsize, c is variable-size with an upper bound of 10.

Sometimes, using coder.varsize changes the classification of a cell array from heterogeneous to homogeneous. Consider this code:

function y =  mycell()
%#codegen
c = {1 [2 3]};
y = c{2};
end

The code generator classifies c as heterogeneous because the elements have different sizes. c is fixed-size with dimensions 1-by-2. If you use coder.varsize with c, it becomes homogeneous. For example:

function y =  mycell()
%#codegen
c = {1 [2 3]};
coder.varsize('c', [1 10], [0 1]);
y = c{2};
end

c becomes a variable-size homogeneous cell array with dimensions 1-by-:10.

To force c to be homogeneous, but not variable-size, specify that none of the dimensions vary. For example:

function y =  mycell()
%#codegen
c = {1 [2 3]};
coder.varsize('c', [1 2], [0 0]);
y = c{2};
end 