필터 지우기
필터 지우기

How to do sort rows more efficiently.

조회 수: 3 (최근 30일)
C Zeng
C Zeng 2013년 5월 28일
Hi, all!
I plan to sort rows to an numerical matrix. First sort them in descending order based on first column, then if there is a tie, sort those in the tie in descending order on second column, and so on(if tie sort on the next column).
Generally, it is possible to do this kinder of sorting but I notice "sortrows" command and it can sort rows based on which column. But is there a easier way to do my algorithm described above?
Thanks.

채택된 답변

Jan
Jan 2013년 5월 28일
편집: Jan 2013년 5월 28일
I cannot imagine that there is any easier method than sortrows:
x = randi(4, 8, 8);
y = sortrows(x);
[EDITED] For large arrays like randi(4, 1e5, 10) this is about 10% faster than sortrows:
function [y, index] = leanSortRows(x)
[v, index] = sort(x(:, n)); %#ok<ASGLU>
for k = n-1:-1:1
[v, index2] = sort(x(index, k)); %#ok<ASGLU>
index = index(index2);
end
y = x(index, :);
This is similar to the fallback for backward sorting. The MEX-function sortrows.c, which called for standard cases uses the quicksort algorithm of the C-libs, which are obviously slower than Matlab's built-in SORT.
  댓글 수: 1
C Zeng
C Zeng 2013년 5월 28일
Thanks, Jan! Let me think it over again.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by