如何获取矩阵元胞数组中的所有唯一值?

How to get all unique values in a cell array of matrices?

我想获取 A 中的所有唯一值,其中 A 是不同形状和大小的矩阵元胞数组:

A = {[], 1, [2 3], [4 5; 6 7]};
U = [];
for ii = 1: numel(A)
    a = A{ii};
    U = [U; a(:)];
end
U = unique(U);

那个returns:

U =
 1     2     3     4     5     6     7

如果 A 中的所有元素都是行向量,我可以使用 [A{:}] 如:

U = unique([A{1:3}]);

那个returns:

U =
 1     2     3

但在我的例子中它抛出一个异常:

Error using horzcat

Dimensions of matrices being concatenated are not consistent.

那么如何避免 for 循环?

您可以使用 cellfun 重塑单元格中的所有元素。

U = unique(cell2mat(cellfun(@(x)reshape(x,1,numel(x)),A, 'UniformOutput', false)));

或避免reshape

U = unique(cell2mat(cellfun(@(x)x(:).',A, 'UniformOutput', false)));

我们可以这样走:

A = {[], 1, [2 3], [2 0; 4 5; 6 7]};
AA = cellfun( @(x) unique(x(:)), A, 'UniformOutput' , false)
res = unique(cat(1, AA{:}))
  1. 首先为每个单元格创建唯一的数组 - 它让我们避免将所有单元格转换为数字,只是唯一的值。
  2. 让我们将元胞数组转换为一个数值数组 - cat(1, AA{:})
  3. 通过此结果数组查找唯一值。