Finding most frequent element in a cell array without using unique function?
1 view (last 30 days)
Show older comments
Hello I am stuck trying to figure small block of code. I have cell array of repeating strings and numbers(class double) corresponding to the strings.
Name Score
'John' 90
'Mat' 99
'John' 98
'Tonny' 88
'Carl' 99
'Rem' 88
'Tonny' 99
How do I count the number of times the same name appears and the total score they got. For instance the total score for 'John' would be 188. I know you can use unique function to do it, but is there other way to do it beside using unique. It would be great if you guys could help me out. Thanks
0 Comments
Accepted Answer
Geoff Hayes
on 7 Mar 2015
Kratos - if you are unable to use unique (it is unclear why) then if the above data is in a cell array as
data = { 'John' 90
'Mat' 99
'John' 98
'Tonny' 88
'Carl' 99
'Rem' 88
'Tonny' 99};
sort the data in the first column using sortrows. Then iterate over each row and compare (using strcmp) the name in that row with the name in the previous row. If identical, then sum the score with that from the previous row and continue in this fashion until you encounter a row with a different name. At that point, all elements prior to this one have the same name and so you can write out the total score for that individual. Now start with the new name and continue with the next row. Are the two names identical? If so, add the two scores and continue. If not, then write out the score for the previous name and continue.
0 Comments
More Answers (0)
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!