Finding most frequent element in a cell array without using unique function?

1 次查看(过去 30 天)
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

采纳的回答

Geoff Hayes
Geoff Hayes 2015-3-7
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 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by