필터 지우기
필터 지우기

sorting without moving NaNs

조회 수: 5 (최근 30일)
Sebastiano delre
Sebastiano delre 2013년 12월 20일
댓글: Image Analyst 2013년 12월 20일
How can I sort an array without moving the NaN elements?
I have A=[20 10 NaN 66 NaN 12] and I would like to get A=[66 20 NaN 12 NaN 10]. Thank you for your help. Alessio.

채택된 답변

Jos (10584)
Jos (10584) 2013년 12월 20일
편집: Jos (10584) 2013년 12월 20일
Use a variant of the same trick:
A=[6 20; 10 10; 3 NaN; 20 66; 4 NaN; 7 12]
B = flipud(sortrows(A,[2 1])) ; % descending sortrows based on 2nd column
A(~isnan(A(:,2)),:) = B(~isnan(B(:,2)),:)
  댓글 수: 1
Image Analyst
Image Analyst 2013년 12월 20일
Sebastiano's "Answer" moved here since it's a comment, not an answer:
Thanks a lot, it works perfectly!

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

추가 답변 (4개)

Jos (10584)
Jos (10584) 2013년 12월 20일
편집: Jos (10584) 2013년 12월 20일
A=[20 10 NaN 66 NaN 12]
B = sort(A,'descend')
A(~isnan(A)) = B(~isnan(B))

Azzi Abdelmalek
Azzi Abdelmalek 2013년 12월 20일
편집: Azzi Abdelmalek 2013년 12월 20일
A=[20 10 NaN 66 NaN 12]
idx=~isnan(A);
B=sort(A,'descend');
B(isnan(B))=[];
A(idx)=B

Jan
Jan 2013년 12월 20일
편집: Jan 2013년 12월 20일
If A is large and contains a lot of NaN's, excluding them from the sorting can save some time:
A = [20 10 NaN 66 NaN 12]
idx = ~isnan(A);
A(idx) = sort(A(idx), 'descend');
  댓글 수: 1
Jos (10584)
Jos (10584) 2013년 12월 20일
I doubt that excluding NaNs is faster, Jan. Increasing the proportion of NaNs seems to have little effect, or even a positive effect sometimes:
a = randperm(1e7) ; a(a(1:1e1)) = NaN ; tic ; sort(a) ; toc ;
a = randperm(1e7) ; a(a(1:1e5)) = NaN ; tic ; sort(a) ; toc ;

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


Sebastiano delre
Sebastiano delre 2013년 12월 20일
I am sorry. Actually I wrongly state my problem. I have A=[6 20; 10 10; 3 NaN; 20 66; 4 NaN; 7 12] and I would like to get A=[20 66; 6 20; 3 NaN; 7 12; 4 NaN; 10 10]. This means I would like to sort the rows of the matrix in a descending order based on the second column and without moving the rows with the NaN elements in the second column. I would like to use sortrows. Sorry again. Alessio.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by