sorting without moving NaNs
显示 更早的评论
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.
采纳的回答
更多回答(4 个)
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
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
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)
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 ;
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!