MATLAB: How to extract the values of the data that constitute a certain percentile

MATLAB

I have been using the 'prctile' function in MATLAB R2017b to find certain percentiles of my data. I am wondering if there is a way to automatically return the values that constitute these percentiles.
For example, I am getting the 10th, 20th and 30th percentiles of my data by the following line:
>> p10 = prctile(data, [10 20 30]);
How can I extract the values of 'data' that are in each of these percentiles?

Best Answer

The 'prctile' function does not provide an automatic way to extract the values of your data that constitute a certain percentile. However, you can use 'prctile' along with another couple lines of code to obtain these values. Below are a couple examples:
Method 1:
>> m = rand(1, 20); % generate a random list of numbers
>> percentiles = prctile(m, [10 20 30]);
>> vals10 = m(m <= percentiles(1)); % values in the 10th percentile
>> vals20 = m(m <= percentiles(2)); % values in the 20th percentile
>> vals30 = m(m <= percentiles(3)); % values in the 30th percentiles
Method 2:
>> m = rand(1, 20);
>> mSorted = sort(m);
>> vals10 = mSorted(1:floor(end * 0.1));
>> vals20 = mSorted(1:floor(end * 0.2));
>> vals30 = mSorted(1:floor(end * 0.3));
Note: Method 2 does not calculate the percentiles, just the values that constitute each percentile. It also does not keep the data in its original order.