Hi! I'm trying to extract the top N elements of each kind in a matrix
1 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Guillaume
2016-3-2
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{:})
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!