Use the third output of unique
, and make sure that those input strings are in a cell
array. The third output of unique
is pretty cool, because it assigns a unique ID for each unique quantity that is seen in the input. As such, if you had a sequence of characters from a
to e
, it would assign a unique ID for each unique character that it has found, between 1 and 5. Also, the first output of unique
gives you an array that only contains the unique quantities seen in the input.
You can then use accumarray
on this third output to count how many times you see a particular country over all countries listed.
val = {'USA'; 'USA'; 'France'; 'USA'; 'France'};
[countries,~,id] = unique(val);
counts = accumarray(id, 1);
I get:
counts =
2
3
Also for countries
:
countries =
'France'
'USA'
Notice that each element of counts
corresponds to how many times you see that particular country in the same position as the country in countries
, so France is seen 2 times, and USA 3 times.