If you do not need an order of elements with equal frequency, you can do this like this:
>> freq = accumarray(matrix(:,3), 1); >> [~, ind] = sort(freq(matrix(:, 3)), 1, 'descend'); % index that sorts matrix >> matrix(ind, :) % reshuffle matrix to sort ans = 3 2 3 5 3 3 4 2 3 2 4 3 2 5 4 5 5 4 3 6 4 1 4 2 4 3 2 1 3 1
If you don't care, you need to pre-sort the matrix first. Since matlab sort is stable , this will keep the order of the elements equal in the second sort.
>> matrix = sortrows(matrix, 1) matrix = 1 3 1 1 4 2 2 5 4 2 4 3 3 2 3 3 6 4 4 3 2 4 2 3 5 5 4 5 3 3 >> freq = accumarray(matrix(:,3),1); >> [~, ind] = sort(freq(matrix(:,3)), 1, 'descend'); >> matrix(ind, :) ans = 2 4 3 3 2 3 4 2 3 5 3 3 2 5 4 3 6 4 5 5 4 1 4 2 4 3 2 1 3 1
source share