How to create a Matrix which shows a ranking of values
Show older comments
Hey guys,
sorry for this bad title but i didnt know how to express this differently.
I currently have a vector of 19 names (e.g. Lisa, Paul, Franz, Lisa,...). Some names appear more often than one time. From this vector I Need a Code that gives me a table. One column of this table should show how many times a Name appears and in the other row you can see the Name. This table should be in a descending order.
It should look like:
Count (Column 1) II Name (Column 2)
- 7 II Lisa
- 4 II Paul
- 2 II Michael
- ...
Can anyone of you help me to write this Code? Would really appreciate your help :)
Best Florian
Accepted Answer
More Answers (2)
One way,
>> names={'Lisa','Paul','Lisa','Jane','Lisa','Jane','Robert'};
>> [col2,i,j]=unique(names);
>> col1=histcounts(j);
>> table(col1(:),col2(:),'VariableNames',{'Count','Name'})ans =
Count Name
_____ ________ 2 'Jane'
3 'Lisa'
1 'Paul'
1 'Robert'
Geoff Hayes
on 13 Nov 2015
Florian - suppose your list of names is a cell array
listOfNames = {'Lisa', 'Paul', 'Franz', 'Lisa', 'Lisa', 'Michael', 'Paul'};
Using the unique function, you can get the unique names from the list as
uniqueNames = unique(listOfNames);
Now, use cellfun to apply an anonymous function to each unique name. The anonymous function will count each occurrence of the unique name in listOfNames, and cellfun will return a list of the counts for each.
nameOccurences = cellfun(@(x)sum(strcmp(listOfNames,x)), uniqueNames);
So all you need to do is to concatenate the occurrence/counts for each names and sort in descending order. First, do the sort on the nameOccurrences numeric array to get the sorted array and (more importantly) the indices of the sorted elements
[sortedData,I] = sort(nameOccurences,'descend');
Now, use the indices I to create your matrix of "ranked" values
rankedNames = [num2cell(nameOccurences(I)') uniqueNames(I)'];
which gives
rankedNames =
[3] 'Lisa'
[2] 'Paul'
[1] 'Franz'
[1] 'Michael'
Categories
Find more on Shifting and Sorting Matrices 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!