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!

采纳的回答

Guillaume
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{:})
  2 个评论
Joshua Santiago
Joshua Santiago 2016-3-2
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);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by