Sorting NaN

32 visualizaciones (últimos 30 días)
Andy
Andy el 12 de Abr. de 2012
Comentada: Steven Lord el 18 de Sept. de 2018
say if i have a matrix a:
a=[1 2 3;4 5 6;7 8 9;NaN NaN NaN]
i want to sort this in descending order, so i use
sort(a,1,'descend')
but the problem is, matlab puts the NaN at the top, is there a way to make it so that NaN is at the bottom? Thanks

Respuesta aceptada

Matt Tearle
Matt Tearle el 12 de Abr. de 2012
As long as you don't have any -Inf values in a, you could always do a quick hack:
a=[1 2 3;4 5 6;7 8 9;NaN NaN NaN]
a(isnan(a)) = -Inf;
a = sort(a,1,'descend');
a(isinf(a)) = NaN

Más respuestas (3)

Huw S
Huw S el 18 de Sept. de 2018
Very late to this for the original poster, but for anyone later looking how to do this....
It's in the matlab functionality.
sort(a,'descend','MissingPlacement','last')
  1 comentario
Steven Lord
Steven Lord el 18 de Sept. de 2018
That functionality was introduced in release R2017a. While I agree that's a good way to solve the problem now, it was not an option when the question was originally asked in 2012.

Iniciar sesión para comentar.


Matt Kindig
Matt Kindig el 12 de Abr. de 2012
You could do something like this:
a=[1 2 3;4 5 6;7 8 9;NaN NaN NaN];
a= sort(a,1,'descend');
in = any( isnan(a),2);
a = [ a(~in,:); a(in,:)];

Kye Taylor
Kye Taylor el 12 de Abr. de 2012
This will work
newA = a; % copy original matrix
isANanRow = any(isnan(a),2); % find rows that have a nan in them
% move those nan rows to the end
newA(end-nnz(isANanRow)+1:end,:) = a(isANanRow,:);
% sort nonnan rows and place at top of newA array
newA(1:nnz(~isANanRow),:) = sort(a(~isANanRow,:),1,'descend');

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by