Search code examples
matlabuniqueaccumarray

Count occurences of strings in column - Matlab


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.


Solution

  • 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