Andi
Andi

Reputation: 4899

Sort matrix with NaNs, extract index vectors and move NaNs to the end

mockup = [3,5,nan,2,4,nan,10,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]

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]

Upvotes: 2

Views: 115

Answers (1)

Suever
Suever

Reputation: 65460

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

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;

Upvotes: 5

Related Questions