How to get a new cell array containing the repeated elements in an original cell?

2 views (last 30 days)
For example if I have an original cell as
celloriginal={'apple','bird','cat','bird','zoo','bird','cat'};
and I want to obtain a new cell which contains the elements, 'bird' and 'cat', that appear multiple times in the original cell
cellnew={'bird','cat'}
I have tried unique(celloriginal), but got no clue what to do next. Help would be really appreciated.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 15 Nov 2017
Edited: Andrei Bobrov on 15 Nov 2017
[g,val] = findgroups(celloriginal);
out = val(histcounts(g,1:max(g)+1)>1);
or
[a,~,c] = unique(celloriginal);
out = a(accumarray(c,1)>1);
  1 Comment
YU ZHU
YU ZHU on 15 Nov 2017
Thank you! What if I only want the elements that repeat the most times. for example
celloriginal={'apple','bird','bird','cat','zoo','bird','bear','bear','bear','cat'}
and cell new contains only 'bird' and 'bear',which appears 3 times, since 'cat' only appears 2 times.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!