Borrar filtros
Borrar filtros

group an array according a condition

3 visualizaciones (últimos 30 días)
eric capnu
eric capnu el 9 de Ag. de 2017
Comentada: eric capnu el 1 de Sept. de 2017
Hi everyone
i have an array like this
A=
2 10 10.1 12 14 110
2 10.1 11 12 15 145
3 12 12 12 24 223
3 12 11.4 11 23 100
3 10 12 20 18 211
4 9 23 11 11 98
I want to create a new B array where i get the maximum value of each column according to the first column value
B=
2 10.1 11 12 15 145
3 12 12 20 24 223
4 9 23 11 11 98
i don´t want to use loops. is there a way to do it by using just matlab functions?
thanks in advance

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 9 de Ag. de 2017
Editada: Andrei Bobrov el 10 de Ag. de 2017
B_table = varfun(@max,array2table(A),'GroupingVariables','A1')
or
B = splitapply(@(x)max(x,[],1),A,findgroups(A(:,1)));
or
g = findgroups(A(:,1)); % or >> [~,~,g] = unique(A(:,1))
[ii,jj] = ndgrid(g,1:size(A,2));
B = accumarray([ii(:),jj(:)],A(:),[],@max);
  2 comentarios
John BG
John BG el 10 de Ag. de 2017
Editada: John BG el 10 de Ag. de 2017
and then back to array
B=table2array(Btable)
B =
2.0000 2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 1.0000 9.0000 23.0000 11.0000 11.0000 98.0000
no need for the frequencies
B(:,2)=[]
B =
2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 9.0000 23.0000 11.0000 11.0000 98.0000
eric capnu
eric capnu el 1 de Sept. de 2017
thanks mates. that was very useful... and, what if instead of @max it would be the last element or the first element of the range?

Iniciar sesión para comentar.

Más respuestas (1)

Stephen23
Stephen23 el 9 de Ag. de 2017
Editada: Stephen23 el 9 de Ag. de 2017
You could use accumarray:
A = [
2 10 10.1 12 14 110
2 10.1 11 12 15 145
3 12 12 12 24 223
3 12 11.4 11 23 100
3 10 12 20 18 211
4 9 23 11 11 98];
%
[~,~,X] = unique(A(:,1));
V = 1:size(A,1);
fun = @(r){max(A(r,:),[],1)};
C = accumarray(X,V(:),[],fun);
Z = vertcat(C{:})
produces this:
Z =
2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 9.0000 23.0000 11.0000 11.0000 98.0000

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by