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

sorting

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!

Best Answer

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{:})