Code Generation for Categorical Arrays - MATLAB & Simulink (original) (raw)

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, andlarge 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'}); end

Allowed Operations on Categorical Arrays

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

Operation Example Notes
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); double(c(1)); 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 orstring 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]; c(idx); idx = logical([1 1 0]); c(idx); Code generation supports indexing by position, linear indexing, and logical indexing.
concatenation 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: