用NaN排序矩阵,提取索引向量并将NaN移到末尾 [英] Sort matrix with NaNs, extract index vectors and move NaNs to the end
问题描述
mockup = [3,5,nan,2,4,nan,10,nan];
如何在不考虑NaN的情况下按降序对向量进行排序?所得向量的长度必须与mockup
相同,即我需要将所有NaN放在末尾.结果应该像这样:
mockupSorted = [10,5,4,3,2,NaN,NaN,NaN]
How can I sort this vector in a descending order while ignoring the NaNs? The resulting vector must have the same length as mockup
, i.e. I need to put all NaNs at the end. The result should like like this:
mockupSorted = [10,5,4,3,2,NaN,NaN,NaN]
实际上,我对各个索引感兴趣,即sort
函数的第二个输出向量.所以,我在寻找
mockupSortedIdx = [7,2,5,1,4,NaN,NaN,NaN]
Actually, I am interested in the respective indices, i.e. the second output vector of the sort
function. So, I am looking for
mockupSortedIdx = [7,2,5,1,4,NaN,NaN,NaN]
推荐答案
您可以使用sort
的两个输出,然后使用isnan
修改两个输出的顺序.
You can use the two outputs of sort
and then use isnan
to modify the ordering of the two outputs.
[vals, inds] = sort(mockup, 'descend');
bool = isnan(vals);
mocksorted = [vals(~bool), vals(bool)];
% 10 5 4 3 2 NaN NaN NaN
mocksortedind = [inds(~bool), vals(bool)];
% 7 2 5 1 4 NaN NaN NaN
另一种选择是使用ascend
排序,并对mockup
的负数进行排序,因为ascend
排序会将NaN
值放在末尾.
The other option is to use ascend
sort and just sort the negative of mockup
since the ascend
sort will place the NaN
values at the end.
[vals, inds] = sort(-mockup);
mocksorted = -vals;
mocksortedind = inds;
这篇关于用NaN排序矩阵,提取索引向量并将NaN移到末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!