필터 지우기
필터 지우기

How to find the number of different strings in a cell array?

조회 수: 146 (최근 30일)
Faranak
Faranak 2017년 10월 3일
편집: Cedric 2017년 10월 3일
Hi, I have a cell with different strings. I don't know what are those strings and how many times they are repeated. I want to find the names of strings and find how many they are repeated. For example: c={'a' 'a' 'a' 'a' 'b' 'b' 'b' 'c' 'c' 'd' 'e'}; I want the answer to say that strings are a,b,c,d,e and the numbers they are repeating are 4,3,2,1,1.
I tried strfind command but it is good for a time that you know what are the strings (which I don't know what are the strings!). I tried strcmp command to find how many each are repeated. But still I have problem with finding the strings! Can anyone help me?
Thanks

채택된 답변

Cedric
Cedric 2017년 10월 3일
편집: Cedric 2017년 10월 3일
Use
uc = unique(c) ;
to get a cell array of unique strings, and its length is their count.
If you need a stat of repetition, use the 2nd or 3rd output of UNIQUE and accumulate ones using it as IDs in acall to ACCUMARRAY.
I can't test right now, but something like
[uc, ~, idc] = unique( c ) ;
counts = accumarray( idc, ones(size(idc)) ) ;
  댓글 수: 2
Faranak
Faranak 2017년 10월 3일
Thank you so much. It was perfect.
Cedric
Cedric 2017년 10월 3일
편집: Cedric 2017년 10월 3일
My pleasure! Look at Walter's answer and ImageAnalyst example; FINDGROUPS and HISTCOUNTS may be simpler to (re-)understand if you look back at your code in a few years.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 10월 3일
For R2015b or later, use findgroups()
  댓글 수: 1
Image Analyst
Image Analyst 2017년 10월 3일
E.g.
c={'a' 'a' 'a' 'a' 'b' 'b' 'b' 'c' 'c' 'd' 'e' 'a' 'a' };
[d, id] = findgroups(c)
counts = histcounts(d)
d =
1 1 1 1 2 2 2 3 3 4 5 1 1
id =
1×5 cell array
{'a'} {'b'} {'c'} {'d'} {'e'}
counts =
6 3 2 1 1

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by