Unique cell vectors

六眼飞鱼酱① 提交于 2019-12-02 07:03:21

Here a solution :

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

To transform them back to vector :

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

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!