Question

I try to find unique arrays in a cell array. Suppose I have 6 cells with the following vectors:

a{1}=[1 2];
a{2}=[1 2 3];
a{3}=[2 3 4];
a{4}=[1 2];
a{5}=[1 2 3];
a{6}=[2 3 4];

Then the result should be [1 2], [1 2 3] and [2 3 4]. I used u=(cellfun(@unique,a,'Un',0)), but it doesn't work, How can I do this?

Was it helpful?

Solution 2

Here a solution :

u = unique(cellfun(@num2str,a,'Un',0));

To transform them back to vector :

u2 = cellfun(@str2num,u,'Un',0);

OTHER TIPS

Here is a way to stay numeric (without converting to strings):

ne = cellfun(@numel,a);
C = accumarray(ne(:),1:numel(a),[],@(x) {unique(vertcat(a{x}),'rows')});
C = C(~cellfun(@isempty,C));

C{1}
ans =
     1     2

C{2}
ans =
     1     2     3
     2     3     4

Each cell in a needs to contain a row vector.

Reorganize the output if needed:

m2c = @(x) mat2cell(x,ones(size(x,1),1),size(x,2));
C2 = cellfun(m2c,C,'uni',0);
C2 = vertcat(C2{:})

C2{1}
ans =
     1     2

C2{2}
ans =
     1     2     3

C2{3}
ans =
     2     3     4

Another solution which doesn't involve converting to strings:

n = numel(a);
[i1 i2] = ndgrid(1:n); %// generate all pairs of elements (their indices, really)
equals = arrayfun(@(k) isequal(a{i1(k)},a{i2(k)}), 1:n^2); %// are they equal?
equals = tril(reshape(equals,n,n),-1); %// make non-symmetrical and non-reflexive
u = a(~any(equals)); %// if two elements are equal, remove one of them
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top