Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用matlab在矩阵中找到唯一(非重复)值_Matlab_Unique - Fatal编程技术网

如何使用matlab在矩阵中找到唯一(非重复)值

如何使用matlab在矩阵中找到唯一(非重复)值,matlab,unique,Matlab,Unique,各位。假设我有以下(3x3)矩阵A: 我的问题是如何使用matlab找出矩阵中的唯一值? 在这种情况下,结果应该是1。 我试过用这个 value=unique(A) 但它返回的向量{0;1;3}不是我想要的 我非常感谢你们能帮我解决这个问题。谢谢大家! 我通常喜欢的计数方法使用sort和diff,如下所示: [x,sortinds] = sort(A(:)); dx = diff(x); thecount = diff(find([1; dx; 1])); uniqueinds = [find

各位。假设我有以下(3x3)矩阵A:

我的问题是如何使用matlab找出矩阵中的唯一值? 在这种情况下,结果应该是1。 我试过用这个

value=unique(A)
但它返回的向量{0;1;3}不是我想要的


我非常感谢你们能帮我解决这个问题。谢谢大家!

我通常喜欢的计数方法使用
sort
diff
,如下所示:

[x,sortinds] = sort(A(:));
dx = diff(x);
thecount = diff(find([1; dx; 1]));
uniqueinds = [find(dx); numel(x)];
countwhat = x(uniqueinds);
然后,只需一次出现即可获取值:

lonelyValues = countwhat(thecount==1)
如果需要这些值在矩阵中的位置:

valueInds = sortinds(uniqueinds(thecount==1))
[valRows,valCols] = ind2sub(size(A),valueInds)

如果您希望矩阵中有任何
NaN
和/或
Inf
值,您必须进行额外的簿记,但想法是相同的。

这里有一个单行替代方案:

find(histc(A(:), 0:3)==1) - 1
或者更一般地说:

find(histc(A(:), min(A(:)):max(A(:)))==1) + min(A(:)) - 1
或者进一步推广(处理浮动)

这是一个短的

value = A(sum(bsxfun(@eq, A(:), A(:).'))==1);

它比较矩阵中的所有元素对,计算它们相等的次数,并返回仅计数一次的元素。

这里是另一种使用
unique()
hist()的替代方法:

计数元素:

[elements,indices,~] = unique(A);              % get each value with index once
counts = hist(A(:), elements);                 % count occurrences of elements within a
uniqueElements = elements(counts==1);          % find unique elements
获取元素:

[elements,indices,~] = unique(A);              % get each value with index once
counts = hist(A(:), elements);                 % count occurrences of elements within a
uniqueElements = elements(counts==1);          % find unique elements
获取索引:

uniqueIndices  =  indices(counts==1);          % find unique indices
[uRow, uCol] = ind2sub(size(A),uniqueIndices); % get row/column representation

这仅适用于矩阵元素为整数的情况,请尝试将示例中的一个零值替换为
-1.5
2.5
。当矩阵的大小较大时,第二行matlab最有效。我的案例是1e6元素。谢谢那是个不错的主意。我总是惊讶于我的旧代码中有多少被
bsxfun
简化了。MathWorks应该更早地引入它。@*-只需注意,在这个解决方案中,有一个大小为
numel(a)*numel(a)
的临时方形矩阵,如果矩阵大小将100+个元素推到正方形,则该矩阵可能会被禁止。它是一个逻辑矩阵,这很有帮助,但意识到这一点仍然很好。。。最近,我发布了一个基于bsxfun的巧妙的解决方案,结果证明作者有一个大数据集,该解决方案不可行。当然,这个3x3示例没有问题!