Yevis
Yevis

Reputation: 63

How to find repeated cell vectors in matlab?

I have n different length cell vectors, call it c{i}, i=1,2,...,n.

I wanna find those c{i} which equal with others, for example:

c{1}=[1 2 3 4 5 6]; c{2}=[1 3 5 7]; c{3}=[2 4 6 8];
c{4}=[1 4 6]; c{5}=[3 7]; c{6}=[2 4 6 8]; c{7}=[1 3 5 7];

I hope I can find [2 4 6 8] and [1 3 5 7] with a simple way instead of using two loops.

Thanks!

Upvotes: 1

Views: 303

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

You can do it with unique. You need to convert vectors to strings, because unique works with cell arrays of strings but not with cell arrays of numeric vectors. After unique, you can count how many strings (vector) are repeated with histc, and them some indexing lets you retrieve the corresponding vectors:

strcell = cellfun(@(e) num2str(e), c, 'uniformoutput', 0); %// convert to strings
[~, ii, jj] = unique(strcell); %// apply unique. Second and third outputs needed
ind = find(histc(jj,min(jj)-.5:max(jj)+.2)>1); %// which appear more than once
result = c(ii(ind)); %// indexing to obtain corresponding original vectors

Upvotes: 1

Related Questions