Count occurences of strings in column - Matlab

2019-08-02 05:34发布

I have a column with the following data:
Size: 100x7

val =

USA
USA
France
USA
France

I want to show the data on pie chart. to do this, I need to know how much USA occur in this column, and so on.
I read about the functions unique,accumarray but I dont success
I would like to get some suggestions how to do that.
Thanks.

4条回答
贼婆χ
2楼-- · 2019-08-02 06:06

This will give you the number of occurrences by using regexp:

unique_countries = unique(regexp(val,'^.*$','lineanchors','match','dotexceptnewline'));

count_unique_countries = zeros(size(unique_countries));
for ii = 1:numel(unique_countries)
    count_unique_countries(ii) = numel(regexp(val,['^' unique_countries{ii} '$'],'lineanchors'));
end

The two output variables are now

unique_countries = 
'France'    'USA'
count_unique_countries =
 1     2
查看更多
霸刀☆藐视天下
3楼-- · 2019-08-02 06:07

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.

查看更多
Evening l夕情丶
4楼-- · 2019-08-02 06:07

If you have the statistics toolbox, you can also do the following:

valnom = nominal(val);
countries = getlabels(valnom);
occurrences = levelcounts(valnom);
查看更多
萌系小妹纸
5楼-- · 2019-08-02 06:08

You can use unique with histc -

%// Get countries and their occurences
[countries,~,id] = unique(cellstr(val),'stable')
occurrences = histc(id,1:max(id))

You can then display the number of occurrences against the country names as a table -

>> table(countries,occurrences)
ans = 
    countries    occurrences
    _________    ___________
    'USA'        3          
    'France'     2       

Display output as a pie chart -

>> pie(occurrences,countries)

enter image description here

查看更多
登录 后发表回答