5

每个人。假设我有以下(3x3)矩阵A:

0 1 3
0 0 3
0 0 0

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

value=unique(A)

但它返回的向量 {0;1;3} 不是我想要的。

如果你们能帮我解决这个问题,我将不胜感激。谢谢!

4

4 回答 4

4

这是一个简短的

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

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

于 2013-10-08T08:48:23.513 回答
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
于 2013-10-08T06:23:30.480 回答
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值,则必须进行额外的簿记,但想法是相同的。

于 2013-10-08T00:49:01.117 回答
1

unique()这是使用and的另一种选择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
于 2014-12-17T20:15:48.533 回答