sorting without moving NaNs
    11 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    Sebastiano delre
 am 20 Dez. 2013
  
    
    
    
    
    Kommentiert: Image Analyst
      
      
 am 20 Dez. 2013
            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.
0 Kommentare
Akzeptierte Antwort
  Jos (10584)
      
      
 am 20 Dez. 2013
        
      Bearbeitet: Jos (10584)
      
      
 am 20 Dez. 2013
  
      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 Kommentar
  Image Analyst
      
      
 am 20 Dez. 2013
				Sebastiano's "Answer" moved here since it's a comment, not an answer:
Thanks a lot, it works perfectly!
Weitere Antworten (4)
  Jos (10584)
      
      
 am 20 Dez. 2013
        
      Bearbeitet: Jos (10584)
      
      
 am 20 Dez. 2013
  
      A=[20 10 NaN 66 NaN 12]
B = sort(A,'descend')
A(~isnan(A)) = B(~isnan(B))
0 Kommentare
  Azzi Abdelmalek
      
      
 am 20 Dez. 2013
        
      Bearbeitet: Azzi Abdelmalek
      
      
 am 20 Dez. 2013
  
      A=[20 10 NaN 66 NaN 12] 
idx=~isnan(A); 
B=sort(A,'descend');
B(isnan(B))=[];
A(idx)=B
0 Kommentare
  Jan
      
      
 am 20 Dez. 2013
        
      Bearbeitet: Jan
      
      
 am 20 Dez. 2013
  
      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 Kommentar
  Jos (10584)
      
      
 am 20 Dez. 2013
				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 ;
Siehe auch
Kategorien
				Mehr zu Logical finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




