Main Content

Code Generation for Categorical Arrays

Categorical arrays store data with values from a finite set of discrete categories. You can specify an order for the categories, but it is not required. A categorical array provides efficient storage and manipulation of nonnumeric data, while also maintaining meaningful names for the values.

When you use categorical arrays with code generation, adhere to these restrictions:

Define Categorical Arrays for Code Generation

For code generation, use the categorical function to create categorical arrays. For example, suppose the input argument to your MATLAB® function is a numeric array of arbitrary size whose elements have values of either 1, 2, or 3. You can convert these values to the categories small, medium, and large and turn the input array into a categorical array, as shown in this code.

function c = foo(x) %#codegen
    c = categorical(x,1:3,{'small','medium','large'});

Allowed Operations on Categorical Arrays

For code generation, you are restricted to the operations on categorical arrays listed in this table.


assignment operator: =

c = categorical(1:3,1:3,{'small','medium','large'});
c(1) = 'large';

Code generation does not support using the assignment operator = to:

  • Delete an element.

  • Expand the size of a categorical array.

  • Add a new category, even when the array is not protected.

relational operators: < > <= >= == ~=

c = categorical(1:3,'Ordinal',true);
tf = c(1) < c(2);

Code generation supports all relational operators.

cast to numeric type

c = categorical(1:3);

Code generation supports casting categorical arrays to arrays of double- or single-precision floating-point numbers, or to integers.

conversion to text

c = categorical(1:3,1:3,{'small','medium','large'});
c1 = cellstr(c(1)); % One element
c2 = cellstr(c);    % Entire array

Code generation does not support using the char or string functions to convert categorical values to text.

To convert one or more elements of a categorical array to text, use the cellstr function.

indexing operation

c = categorical(1:3,1:3,{'small','medium','large'});
idx = [1 2];
idx = logical([1 1 0]);

Code generation supports indexing by position, linear indexing, and logical indexing.


c1 = categorical(1:3,1:3,{'small','medium','large'});
c2 = categorical(4:6,[2 1 4],{'medium','small','extra-large'});
c = [c1 c2];

Code generation supports concatenation of categorical arrays along any dimension.

MATLAB Toolbox Functions That Support Categorical Arrays

For code generation, you can use categorical arrays with these MATLAB toolbox functions:

Related Topics