大家。假设我有以下(3x3)矩阵A:
0 1 3
0 0 3
0 0 0
我的问题是如何使用matlab找出该矩阵中的唯一值? 在这种情况下,结果应为1。 我试过用过
value=unique(A)
但它返回了一个向量{0; 1; 3}并不是我想要的。
如果你们能帮我解决这个问题,我非常感谢。谢谢!
答案 0 :(得分:4)
这是一个简短的
value = A(sum(bsxfun(@eq, A(:), A(:).'))==1);
它比较矩阵中的所有元素对,并计算它们相等的次数,并返回仅计数一次的那些元素。
答案 1 :(得分:2)
以下是一行替代方案:
find(histc(A(:), 0:3)==1) - 1
或更一般地说:
find(histc(A(:), min(A(:)):max(A(:)))==1) + min(A(:)) - 1
或者进一步概括(处理花车)
p = 0.1; %//Set a precision.
(find(histc(A(:), min(A(:)):p:max(A(:)))==1) + min(A(:)) - 1)*p
答案 2 :(得分:1)
计算方法我通常更喜欢使用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
值,您必须进行额外的记账,但想法是一样的。
答案 3 :(得分: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
获取指数:
uniqueIndices = indices(counts==1); % find unique indices
[uRow, uCol] = ind2sub(size(A),uniqueIndices); % get row/column representation