分类数组的代码生成
分类数组存储其值来自离散类别有限集合的数据。您可以指定类别的顺序,但这不是必需的。分类数组可用来高效地存储和处理非数值数据,同时还为数值赋予有意义的名称。
在代码生成中使用分类数组时,请遵守以下限制:
为代码生成定义分类数组
对于代码生成,请使用 categorical 函数创建分类数组。例如,假设您的 MATLAB® 函数的输入参量是任意大小的数值数组,其元素的值为 1、2 或 3。您可以将这些值转换为类别 small、medium 和 large,并将输入数组转换为分类数组,如以下代码所示。
function c = foo(x) %#codegen c = categorical(x,1:3,{'small','medium','large'}); end
允许对分类数组执行的操作
对于代码生成,您只能对分类数组执行下表中列出的操作。
| 运算 | 示例 | 附注 |
|---|---|---|
赋值运算符: |
c = categorical(1:3,1:3,{'small','medium','large'});
c(1) = 'large';
| 代码生成不支持使用赋值运算符
|
关系运算符: |
c = categorical(1:3,'Ordinal',true);
tf = c(1) < c(2);
| 代码生成支持所有关系运算符。 |
转换为数值类型 |
c = categorical(1:3); double(c(1)); | 代码生成支持将分类数组转换为双精度或单精度浮点数数组,或转换为整数。 |
转换为文本 |
c = categorical(1:3,1:3,{'small','medium','large'});
c1 = cellstr(c(1)); % One element
c2 = cellstr(c); % Entire array
| 代码生成不支持使用 要将分类数组中的一个或多个元素转换为文本,请使用 |
索引操作 |
c = categorical(1:3,1:3,{'small','medium','large'});
idx = [1 2];
c(idx);
idx = logical([1 1 0]);
c(idx);
| 代码生成支持按位置索引、线性索引和逻辑索引。 |
串联 |
c1 = categorical(1:3,1:3,{'small','medium','large'});
c2 = categorical(4:6,[2 1 4],{'medium','small','extra-large'});
c = [c1 c2];
| 代码生成支持沿任一维度串联分类数组。 |
支持分类数组的 MATLAB 工具箱函数
对于代码生成,您可以将分类数组与以下 MATLAB 工具箱函数结合使用: