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
0 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!