Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a unique (non-repeated) value in a matrix by using matlab

Tags:

unique

matlab

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!

like image 866
Kelly Gan Avatar asked Oct 08 '13 00:10

Kelly Gan


4 Answers

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.

like image 91
Mohsen Nosratinia Avatar answered Nov 01 '22 09:11

Mohsen Nosratinia


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
like image 31
Dan Avatar answered Nov 01 '22 09:11

Dan


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.

like image 27
chappjc Avatar answered Nov 01 '22 11:11

chappjc


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
like image 23
darkdragon Avatar answered Nov 01 '22 10:11

darkdragon