Main Content

比较分类数组元素

此示例演示了如何对分类数组执行关系运算。

基于字符向量元胞数组创建分类数组

创建一个 2×4 的字符向量元胞数组。

C = {'blue' 'red' 'green' 'blue';...
    'blue' 'green' 'green' 'blue'};

colors = categorical(C)
colors = 2x4 categorical
     blue      red        green      blue 
     blue      green      green      blue 

colors 是一个 2×4 的分类数组。

列出分类数组的类别。

categories(colors)
ans = 3x1 cell
    {'blue' }
    {'green'}
    {'red'  }

确定元素是否相等

使用关系运算符 eq (==) 比较 colors 的第一行和第二行。

colors(1,:) == colors(2,:)
ans = 1x4 logical array

   1   0   1   1

两行数据间仅第二列的值有所不同。

比较整个数组与字符向量

将整个分类数组 colors 与字符向量 'blue' 进行比较以查找所有 blue 值的位置。

colors == 'blue'
ans = 2x4 logical array

   1   0   0   1
   1   0   0   1

colors 中有四个蓝色条目,数组的每个角一个。

转换为有序分类数组

colors 中的类别添加数学排序。指定表示色谱排序的类别顺序 red < green < blue

colors = categorical(colors,{'red','green' 'blue'},'Ordinal',true)
colors = 2x4 categorical
     blue      red        green      blue 
     blue      green      green      blue 

分类数组中的元素仍然相同。

列出 colors 中的离散类别。

categories(colors)
ans = 3x1 cell
    {'red'  }
    {'green'}
    {'blue' }

按顺序比较元素

确定 colors 的第一列中的元素是否大于第二列中的元素。

colors(:,1) > colors(:,2)
ans = 2x1 logical array

   1
   1

第一列中的两个值 blue 都大于第二列中的对应值 redgreen

查找 colors 中小于 'blue' 的所有元素。

colors < 'blue'
ans = 2x4 logical array

   0   1   1   0
   0   1   1   0

函数 lt (<) 指示所有 greenred 值为 1 的位置。

另请参阅

|

相关示例

详细信息