Main Content

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.

To make a cell array variable-size:

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

    function z = mycell(n, j)
    %#codegen
    assert (n < 100);
    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 make sure that you assign values to all cell array elements. See Resolve Issue: Cell Array Elements Must Be Fully Defined Before Use (MATLAB Coder).

  • Grow the cell array. For example:

    function z = mycell(n)
    %#codegen
    c = {1 2 3};
    if n > 3
        c = {1 2 3 4};
    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{1};
    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

See Also

Related Topics