everyone. Let's say I have following (3x3)matrix A:
0 1 3
0 0 3
0 0 0
My question is how to find out the unique value in that matrix by using matlab? In this case, the result should be 1. I have tried used the
value=unique(A)
but it returned a vector {0;1;3} is not what I want.
I much appreciate if you guys can help me solve this problem. Thank you!
Here is a short one
value = A(sum(bsxfun(@eq, A(:), A(:).'))==1);
It compares all pairs of elements in the matrix and counts how many times they are equal and returns the ones that have been counted only once.
Here is a one line alternative:
find(histc(A(:), 0:3)==1) - 1
or more generally:
find(histc(A(:), min(A(:)):max(A(:)))==1) + min(A(:)) - 1
OR to generalize it even further (to handle floats)
p = 0.1; %//Set a precision.
(find(histc(A(:), min(A(:)):p:max(A(:)))==1) + min(A(:)) - 1)*p
The method of counting I generally prefer uses sort
and diff
as follows,
[x,sortinds] = sort(A(:));
dx = diff(x);
thecount = diff(find([1; dx; 1]));
uniqueinds = [find(dx); numel(x)];
countwhat = x(uniqueinds);
Then you grab the value(s) with only one occurrence:
lonelyValues = countwhat(thecount==1)
If you want the location of these value(s) in the matrix:
valueInds = sortinds(uniqueinds(thecount==1))
[valRows,valCols] = ind2sub(size(A),valueInds)
If you expect to any NaN
and/or Inf
values in your matrix, you have to do additional bookkeeping, but the idea is the same.
Here is another alternative using unique()
and hist()
:
count elements:
[elements,indices,~] = unique(A); % get each value with index once
counts = hist(A(:), elements); % count occurrences of elements within a
get elements:
uniqueElements = elements(counts==1); % find unique elements
get indices:
uniqueIndices = indices(counts==1); % find unique indices
[uRow, uCol] = ind2sub(size(A),uniqueIndices); % get row/column representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With