Effacer les filtres
Effacer les filtres

group an array according a condition

3 vues (au cours des 30 derniers jours)
eric capnu
eric capnu le 9 Août 2017
Commenté : eric capnu le 1 Sep 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

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 9 Août 2017
Modifié(e) : Andrei Bobrov le 10 Août 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 commentaires
John BG
John BG le 10 Août 2017
Modifié(e) : John BG le 10 Août 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 le 1 Sep 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?

Connectez-vous pour commenter.

Plus de réponses (1)

Stephen23
Stephen23 le 9 Août 2017
Modifié(e) : Stephen23 le 9 Août 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

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by