Cody Problem 38. Return a list sorted by number of occurrences
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
David Hill
2021년 4월 5일
편집: David Hill
2021년 4월 5일
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.
추가 답변 (1개)
Abhinav
2023년 4월 26일
편집: Rik
2023년 4월 26일
function output_array = popularity(input_array)
%% First make unique array
unique_input_array = unique(input_array);
%% Create occurences - keys pair array
table_occurence = zeros(length(unique_input_array),2);
table_occurence(:,2) = unique_input_array';
for i = 1:length(unique_input_array)
occurrence = numel(find(input_array == unique_input_array(i)));
table_occurence(i,1) = occurrence;
end
%% Sort by occurences in descending order
sorted_table = sortrows(table_occurence,'descend');
occurences = sorted_table(:,1);
keys = sorted_table(:,2);
%% Find keys that have same occurences and store sorted keys in new array
occurences_total = unique(occurences,'stable');
output_array = [];
for j = 1:length(occurences_total)
[row,~] = find(occurences == occurences_total(j));
aa = sort(keys(row));
output_array = [output_array, [aa']];
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!