Azzera filtri
Azzera filtri

Find min and max in groups

5 visualizzazioni (ultimi 30 giorni)
Sergio Rojas Blanco
Sergio Rojas Blanco il 14 Mag 2024
I have 2 vectors of equal dimension, A and B. To each value of A corresponds a value of B, but equal values of A can correspond to different values of B.
I need to obtain a cell array, "Min", whose cells are vectors with the indexes of the minimum values of B and another cell array, "Max", with the maximum values. The position in each cell array is indicated by the value of A.
For example, if
A = [12, 11, 12, 5, 3, 10, 5]; B = [0.1, 0.1, 0.1, 0.7, 0.4, 0.3, 0.2]
Then:
Min = {0 ,0 ,5 ,0 ,4 ,0 ,0 ,0 ,0 ,6 ,2 ,(1, 3)}; Max = {0 ,0 ,5 ,0 ,4 ,0 ,0 ,0 ,0 ,0 ,0 ,2 ,(1, 3)}
Because of:
a_1 = 12 ; b_1 = 0.1
a_3 = 12 ; b_3 = 0.1
min(0.1, 0,1) = 0.1 => C_12 = (1, 3); max(0.1, 0.1) = 0.1 => D_12 = (1, 3)
a_2 = 11 ; b_2 = 0.1
min(0.1) = 0.1 => C_11 = (2); max(0.1) = 0.1 => D_11 = 2
...
Intiutively, it seems that it could be done in batch using groups.
Would anyone know how to do it? Thanks in advance

Risposta accettata

Stephen23
Stephen23 il 14 Mag 2024
Modificato: Stephen23 il 14 Mag 2024
A = [12, 11, 12, 5, 3, 10, 5];
B = [0.1, 0.1, 0.1, 0.7, 0.4, 0.3, 0.2];
X = 1:numel(A);
Fmax = @(x){x(max(B(x))==B(x))};
Fmin = @(x){x(min(B(x))==B(x))};
Cmax = accumarray(A(:),X(:),[],Fmax,{0});
Cmax{:}
ans = 0
ans = 0
ans = 5
ans = 0
ans = 4
ans = 0
ans = 0
ans = 0
ans = 0
ans = 6
ans = 2
ans = 2x1
1 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Cmin = accumarray(A(:),X(:),[],Fmin,{0});
Cmin{:}
ans = 0
ans = 0
ans = 5
ans = 0
ans = 7
ans = 0
ans = 0
ans = 0
ans = 0
ans = 6
ans = 2
ans = 2x1
1 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  1 Commento
Sergio Rojas Blanco
Sergio Rojas Blanco il 15 Mag 2024
Thank you very much. it works perfectly and elegantly!
You answer everything :D

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange

Tag

Prodotti


Release

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by