因为您使用的是包含字符串和数字的结构,所以事情并不那么容易。假设您根本无法更改这一点,查找唯一值及其索引的最佳方法是循环遍历指定的元胞数组,并将其内容保存到地图对象中,该对象将存储这些唯一条目存在的索引。
这对于 MATLAB 的 map 结构非常简单,可以按照下面的代码进行。
A = {'hello'; 2; 3; 4; 'hello';2;'hello'}
cellMap = containers.Map();
for i = 1 : numel(A)
mapKey = num2str(A{i});
if cellMap.isKey(mapKey)
tempCell = cellMap(mapKey);
tempCell{numel(tempCell)+1} = i;
cellMap(mapKey) = tempCell;
else
tempCell = cell(1);
tempCell{1} = i;
cellMap(mapKey) = tempCell;
end
end
您可以通过输入cellMap.keys 找到所有唯一值,这将返回
ans =
'2' '3' '4' 'hello'
然后您可以使用这些键通过cellMap('hello') 找出它们在原始数组中出现的位置。
ans =
[1] [5] [7]
完成所有这些后,您可以进行一些转换以恢复原始状态并将内容更多地转换为您想要的格式。
uniqueVals = cellMap.keys;
uniqueIndices = cell(1,numel(uniqueVals));
for i = 1:numel(uniqueVals)
uniqueIndices{i} = cell2mat(cellMap(uniqueVals{i}));
numEquiv = str2double(uniqueVals{i});
if ~isnan(numEquiv)
uniqueVals{i} = numEquiv;
end
end
uniqueVals{4}
uniqueIndices{4}
将返回:
ans =
hello
ans =
1 5 7
另一种选择,可能更简单直接,就是复制您的元胞数组,并将其所有内容转换为字符串格式。这不会立即以您想要的格式返回内容,但它是一个开始
B = cell(size(A));
for i = 1:numel(A)
B{i} = num2str(A{i});
end
[C,~,IC] = unique(B)
然后您可以使用来自unique 的返回来查找索引,但老实说,这一切都已经通过我上面编写的映射代码完成了。