1

So how to count no. of repeated letters occur in certain array>

for example i have a array

a
a
a
c
b
c
c
d
a

how can i know how may a,b,c,and occur? i want an output like this:

Alphabet   count
a           4
c           3
b           1
d           1

so how can i do that? thanks

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
Raldenors
  • 311
  • 1
  • 4
  • 15

1 Answers1

3
arr = {'a' 'a' 'a' 'c' 'b' 'c' 'c' 'd' 'a'}

%// map letters with numbers and count them
count = hist(cellfun(@(x) x - 96,arr))

%// filter result and convert to cell
countCell = num2cell(count(find(count)).') %'

%// get sorted list of unique letters 
letters = unique(arr).' %'

%// output
outpur = [letters countCell]

The solution in the duplicate answer is very neat, applied to your desired output:

[letters,~,subs] = unique(arr)
countCell = num2cell(accumarray(subs(:),1,[],@sum))
output = [letters.' countCell]

It appears to me, that your input array rather looks like:

arr = ['a'; 'a'; 'a'; 'c'; 'b'; 'c'; 'c'; 'd'; 'a']

so change the last line to:

output = [cellstr(letters) countCell]

output = 

    'a'    [4]
    'b'    [1]
    'c'    [3]
    'd'    [1]
Community
  • 1
  • 1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113