Clear Filters
Clear Filters

Hi! I'm trying to extract the top N elements of each kind in a matrix

1 view (last 30 days)
say I have a matrix that looks like [10 1 ; 20 1; 11 2; 29 2; 40 3; 50 1; 100 3; 90 2] now I'd like to get the least N elements of each kind so the output here if N=2 would be [10 1;20 1; 11 2; 23 2; 40 3; 100 3] running out of ideas Thaaaanks!

Accepted Answer

Guillaume
Guillaume on 2 Mar 2016
It's not clear what 'kind' refers to, it looks like it's the value of the second column. In which case,
m = [10 1 ; 20 1; 11 2; 29 2; 40 3; 50 1; 100 3; 90 2];
rowsbycol2 = arrayfun(@(v) m(m(:, 2) == v, :), unique(m(:, 2)), 'UniformOutput', false);
first2values = cellfun(@(r) r(1:2, :), rowsbycol2, 'UniformOutput', false);
first2values = vertcat(first2values{:})
  2 Comments
Joshua Santiago
Joshua Santiago on 2 Mar 2016
hmm is there a way to make it sort of adaptive? since there are some cases where I need to get the top N elements but the number of elements for one kind is less than N. if I set the code to find the first 4 values I get this: ndex exceeds matrix dimensions.
Error in @(r)r(1:4,:)
Error in test (line 3) first4values = cellfun(@(r) r(1:4, :), rowsbycol2, 'UniformOutput', false);

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!