Cody Problem 38. Return a list sorted by number of occurrences

2 views (last 30 days)
Hidd_1
Hidd_1 on 5 Apr 2021
Edited: Hidd_1 on 5 Apr 2021
I found difficulties with the Problem 38 on Cody here is my solution:
function y = popularity(x)
[a,b]=size(x);
s=ones(a,b);
for i=1:b
for j=1:b
if i~=j
if x(i)==x(j)
s(i) = s(i) +1;
end
end
end
end
[A,o]= sort(s,'descend');
for k =1:b
L(k)=x((o(k)));
end
y= unique(L,'stable');
end
Unfortunately it doesn't work for the second case, can anyone help me with that!
Thanks in advance.

Accepted Answer

David Hill
David Hill on 5 Apr 2021
Edited: David Hill on 5 Apr 2021
Take a look at the functions, histcounts(), sort(), and unique(). By combining these functions you can answer the problem in a few lines without any loops.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by