Input = [1,2,1,2,3]; % 1,3索引对应都为‘1’;2,4索引对应都为‘1’
Output = same_index(Input)
function Output = same_index(Input)
% Input = [1,2,1,2,3];
% Output = {[1;3]},{[2;4]}
% 注:Input的输入形式为一行多列或是多行一列的矩阵
[~, ~, ib] = unique(Input);
c = accumarray(ib, (1:numel(Input))', [], @cellhorzcat);
index = zeros(numel(c),1); % 避免使用(end+1)
n = 0;
for i = 1:numel(c)
if numel(c{i,1})>1
n = n+1;
index(n,:) = i;
end
end
index(index==0,:) = [];
Output = c(index,:);
参考:https://www.zhihu.com/question/496060981