查找多个数组的唯一元素

时间:2016-10-10 07:36:56

标签: arrays matlab vector

假设我有3个MAT

X = [ 1 3 9 10 ];
Y = [ 1 9 11 20];
Z = [ 1 3 9 11 ];

现在我想找到只出现一次的值,以及它们属于哪个数组

2 个答案:

答案 0 :(得分:1)

如果您只处理整数并且向量大小相同(所有元素的数量相同),则可以使用histcounts快速搜索唯一元素:

X = [1 -3 9 10];
Y = [1 9 11 20];
Z = [1 3 9 11];
XYZ = [X(:) Y(:) Z(:)]; % one matrix with all vectors as columns
counts = histcounts(XYZ,min(XYZ(:)):max(XYZ(:))+1);
R = min(XYZ(:)):max(XYZ(:)); % range of the data
unkelem = R(counts==1);

然后使用find

的循环找到它们
pos = zeros(size(unkelem));
counter = 1;
for k = unkelem
    [~,pos(counter)] = find(XYZ==k);
    counter = counter+1;
end
result = [unkelem;pos]

你得到:

result =

    -3     3    10    20
     1     3     1     2

所以-3 3 10 20是唯一的,它们分别出现在1 3 1 2向量上。

答案 1 :(得分:1)

我概括EBH's answer以涵盖灵活数量的数组具有不同大小的数组多维数组。此方法也只能处理整数值数组:

function [uniq, id] = uniQ(varargin)
combo = [];
idx = [];
for ii = 1:nargin
    combo = [combo; varargin{ii}(:)]; % merge the arrays
    idx = [idx; ii*ones(numel(varargin{ii}), 1)];
end
counts = histcounts(combo, min(combo):max(combo)+1);
ids = find(counts == 1); % finding index of unique elements in combo
uniq = min(combo) - 1 + ids(:); % constructing array of unique elements in 'counts'
id = zeros(size(uniq));
for ii = 1:numel(uniq)
    ids = find(combo == uniq(ii), 1); % finding index of unique elements in 'combo'
    id(ii) = idx(ids); % assigning the corresponding index
end

这就是它的工作原理:

[uniq, id] = uniQ([9, 4], 15, randi(12,3,3), magic(3))

uniq =

     1
     7
    11
    12
    15


id =

     4
     4
     3
     3
     2