Azzera filtri
Azzera filtri

group an array according a condition

3 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 9 Ago 2017
Modificato: Andrei Bobrov il 10 Ago 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 Commenti
John BG
John BG il 10 Ago 2017
Modificato: John BG il 10 Ago 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 il 1 Set 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?

Accedi per commentare.

Più risposte (1)

Stephen23
Stephen23 il 9 Ago 2017
Modificato: Stephen23 il 9 Ago 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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by