使用NaN对矩阵进行排序,提取索引向量并将NaN移动到最后

And*_*ndi 2 sorting matlab nan

mockup = [3,5,nan,2,4,nan,10,nan];

如何在忽略NaN的同时按降序对此向量进行排序?得到的矢量必须具有相同的长度mockup,即我需要将所有NaN放在最后.结果应该是这样的: mockupSorted = [10,5,4,3,2,NaN,NaN,NaN]

实际上,我对各自的索引感兴趣,即sort函数的第二个输出向量.所以,我在寻找 mockupSortedIdx = [7,2,5,1,4,NaN,NaN,NaN]

Sue*_*ver 5

您可以使用两个输出,sort然后使用它isnan来修改两个输出的顺序.

[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
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用ascendsort并对排序进行排序,mockup因为ascend排序会将NaN值放在最后.

[vals, inds] = sort(-mockup);

mocksorted = -vals;
mocksortedind = inds;
Run Code Online (Sandbox Code Playgroud)