Arrays 查找多个数组的唯一元素

Arrays 查找多个数组的唯一元素,arrays,matlab,vector,Arrays,Matlab,Vector,假设我有3个垫子 X = [ 1 3 9 10 ]; Y = [ 1 9 11 20]; Z = [ 1 3 9 11 ]; 现在,我想找到只出现一次的值,以及它们属于哪个数组。如果您只处理整数,并且向量大小相同(都具有相同数量的元素),则可以使用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 a

假设我有3个垫子

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

现在,我想找到只出现一次的值,以及它们属于哪个数组。如果您只处理整数,并且向量大小相同(都具有相同数量的元素),则可以使用
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
向量上。

我将其推广到灵活数量的数组不同大小的数组多维数组。此方法也只能处理整数值数组:

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

在其中一个向量中出现一次的值,或在计算三个向量时出现一次的值?在你的例子中,没有值在一个向量中出现两次,但是如果你计算三个向量,它们就会出现。很好!我没有时间继续泛化它。