George Matthews
George Matthews

Reputation: 35

Matlab: Count number of unique strings in the file

I need to do the following in Matlab. I have a list of names in tab or comma delimited file. For example,

Gregor M. Suka

Mark A. Pizda

Matthew A. Blyad

Mark A. Pizda

I would like to load this list into Matlab and count the occurrence of each name in the file, i.e., all but Mark A. Pizda would have 1 occurrence and Mark would have 2.

I usually use howmany.m for this, but when I load the array with textscan function, it gives me cell array which I cannot run through howmany.m count.

Any suggestions would be greatly appreciated!

Upvotes: 2

Views: 415

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Assuming you load the file and get the strings in a cell array:

strings = {'Gregor M. Suka', 'Mark A. Pizda', 'Matthew A. Blyad', 'Mark A. Pizda'};
[uniqueStrings, ~, v] = unique(strings(:));
occurrence = accumarray(v,1); %// Or: occurrence = histc(v,unique(v));

This gives

uniqueStrings = 
    'Gregor M. Suka'
    'Mark A. Pizda'
    'Matthew A. Blyad'

occurrence =
     1
     2
     1

Upvotes: 3

Related Questions