Birks
Birks

Reputation: 123

Count amount of time a certain cell name appears in cell array [MATLAB]

Lets say I have the cell array

Z = {'Pizza' 'Hamburger' 'Hamburger' 'Sushi' 'Bacon' 'Hamburger'}

I want to count the amount of time a certain cell name appears, so the output should be something like

Pizza = 1
Hamburger = 3
Sushi = 1
Bacon = 1

is there a way to do this with BASIC (or easily understandable) syntax? I'm extremely new to this so please explain your answer, thanks!

Upvotes: 1

Views: 116

Answers (2)

m7913d
m7913d

Reputation: 11064

You can use categorical to convert your cell array of characters to a finite set of discrete categories. Afterwards, you can use histogram to count how often each category occurs:

Z = {'Pizza' 'Hamburger' 'Hamburger' 'Sushi' 'Bacon' 'Hamburger'};
Z_ = categorical(Z);
h = histogram(Z_);
h.Categories % the different categories
h.Values % the number of occurrence

Alternative 1: histcounts

If you are not interested in the plot, you can use histcounts instead.

[N,categories] = histcounts(Z_);

Alternative 2: summary

If you are only interested to print the result to the screen, you can use summary instead of histogram:

summary(Z_);

Upvotes: 2

sco1
sco1

Reputation: 12214

You can use unique and accumarray to identify the unique words in your array and count their occurrences, printing the results to the console with fprintf.

For example:

Z = {'Pizza' 'Hamburger' 'Hamburger' 'Sushi' 'Bacon' 'Hamburger'};

% Get unique words & their indices in Z
[words, ~, wordidx] = unique(Z);

% Sum occurrences of indices to get count for each word
wordcounts = accumarray(wordidx, 1);

% Loop and print
for ii = 1:numel(words)
    fprintf('%s = %u\n', words{ii}, wordcounts(ii))
end

Which prints:

Bacon = 1
Hamburger = 3
Pizza = 1
Sushi = 1

Note that unique is case sensitive, if mixed cases are possible you should normalize your array of strings with something like lower to avoid issues with the count.

Upvotes: 4

Related Questions