1

Say I have a vector of size 1-by-x called X. I need to keep the 10 percent largest elements of X and set all other elements equal to zero. This is easy with using sort:

X = sort(abs(X),'descend');
DIM = floor(length(X)*(0.1));
X(DIM+1:end) = 0;

but disturbing the order of the original vector X is not allowed (or if I disturb the original order, after zeroing out, I should recover the original order which I don't know how to). How can this be done?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
User32563
  • 113
  • 3

2 Answers2

2

You can use the prctile function to find the 10% you're looking for, and then use logical indexing to set the rest to 0:

X = rand(1e4,1);
TenPrc = prctile(X,90);
X(X<TenPrc) = 0;
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 2
    @Adriaan , I am quite sure that `prctile` works by sorting the values, so it does the same internally as Zep does explicitely. – Nicky Mattsson Jun 28 '17 at 11:52
1

The sort function gives you back the indexes of the sorted array:

DIM = floor(length(X)*(0.9));
[X, idx] = sort(abs(X)); 
X(1:DIM+1) = 0;

% Restore original indexes
X = X(idx);
Zep
  • 1,541
  • 13
  • 21