0
votes

I've got 2 string cell arrays, one is the unique version of the other. I would like to count the number of occurrence of each values in the unique cell array given the other cell array. I got a large cell array so I thought I'd try my best to find answers to a more faster approach as oppose to looping...

An example:

x = {'the'
 'the'
 'aaa'
 'b'
 'the'
 'c'
 'c'
 'd'
 'aaa'}

y=unique(x)

I am looking for an output in any form that contains something like the following:

'aaa' = 2
'b'   = 1
'c'   = 2
'd'   = 1
'the' = 3

Any ideas?

1

1 Answers

3
votes

One way is to count the indices unique finds:

[y, ~, idx] = unique(x);
counts = histc(idx, 1:length(y));

which gives

counts =

   2
   1
   2
   1
   3

in the same order as y.

histc is my default fallback for counting things, but the function I always forget about is probably better in this case:

counts = accumarray(idx, 1);

should give the same result and is probably more efficient.