Control Whether a Cell Array Is Variable-Size - MATLAB & Simulink (original) (raw)
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 thecoder.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])
See Specify Variable-Size Cell Array Inputs. - In the MATLAB® Coder™ app, select 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 usingcell
, you must make sure that you assign values to all cell array elements. See Resolve Issue: Cell Array Elements Must Be Fully Defined Before Use. - 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
Withoutcoder.varsize
,c
is fixed-size with dimensions 1-by-3. Withcoder.varsize
,c
is variable-size with an upper bound of 10.
Sometimes, usingcoder.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 classifiesc
as heterogeneous because the elements have different sizes.c
is fixed-size with dimensions 1-by-2. If you usecoder.varsize
withc
, it becomes homogeneous. For example:
function y = mycell()
%#codegen
c = {1 [2 3]};
coder.varsize('c', [1 10], [0 1]);
y = c{2};
endc
becomes a variable-size homogeneous cell array with dimensions 1-by-:10.
To forcec
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
See Also
coder.CellType | coder.varsize