Counting every single symbol in string
Afficher commentaires plus anciens
Hello everybody, I'm trying to solve the problem with counting symbols in a string. I have to count every single symbol in sting and write them in a command window. My idea is to use ASCII to transfer every single symbol to an ASCII code and then count the frequency of occurrence. But I dont know if there is some command to cover that huge scale of symbols and count each of them. Do you have guys any idea? Thank you for your time!
Réponses (2)
[c,~,idx]=unique(s); % unique elements, location in the string 's'
n=histcounts(idx,numel(c)); % count how many of each
Above keeps case separate; 'a' and 'A' will be different. If they're to be the same then use
u=unique(lower(s));
2 commentaires
Walter Roberson
le 4 Juin 2018
You do not use u after you calculate it?
I am not sure why you call unique twice?
dpb
le 4 Juin 2018
changed horses in midstream, Walter, didn't realize hadn't elided first line; the steenkin' edit window is so funky. :(
Walter Roberson
le 4 Juin 2018
The short method of counting is
n = accumarray(1+TheCharacterVector(:), 1);
The count for the ASCII code K would be in array entry K+1. You could proceed from there to
[CODE, ~, count] = find(n);
Symbol = char(CODE-1);
But unique is cool too:
[Symbol, ~, bin] = unique(TheCharacterVector(:));
count = accumarray(bin, 1);
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!