Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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!

Respuesta aceptada

Guillaume
Guillaume el 2 de Mzo. de 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 comentarios
Joshua Santiago
Joshua Santiago el 2 de Mzo. de 2016
yup the value of the second value :D it works, thaaaaanks
Joshua Santiago
Joshua Santiago el 2 de Mzo. de 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);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by