0

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.