user1205030
user1205030

Reputation: 225

Matlab: how to sort data descent excluding NaN

Say I have a row:

NaN 29.99 30.00 NaN 24.32 NaN ...............

How can I sort the data in descending order and select the top 10% largest number?

The 'sort' function will put NaN as the "largest"~~~ how can I exclude it?

Thanks!!

Upvotes: 3

Views: 4545

Answers (4)

KAE
KAE

Reputation: 855

[~, iSort] = sort(x, 'descend'); % Sort x including NaNs
iSort(isnan(x(iSort))) = []; % Now remove indices to sorted x which are NaNs

Upvotes: 0

yuk
yuk

Reputation: 19880

If you just need to select the top 10% largest numbers you can use QUANTILE or PRCTILE functions from Statistical Toolbox (no sort needed):

x_largest = x(x >= quantile(x, 0.9));

or

x_largest = x(x >= prctile(x, 90));

Those functions don't take NaNs into account.

Upvotes: 1

Phonon
Phonon

Reputation: 12737

You can first sort the row, and then exclude the NaN's

sorted_row = sorted_row( ~isnan(sorted_row) );

This will remove all NaNs from the sorted row.

Better Yet, to save computations , you should exclude NaNs before you sort.

sorted_row = sort( row(~isnan(row)) );

Upvotes: 2

Werner
Werner

Reputation: 2557

Try using after sort: sorted_row(~isnan(sorted_row))

Upvotes: 1

Related Questions