Effacer les filtres
Effacer les filtres

Find min and max in groups

6 vues (au cours des 30 derniers jours)
Sergio Rojas Blanco
Sergio Rojas Blanco le 14 Mai 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

Réponse acceptée

Stephen23
Stephen23 le 14 Mai 2024
Modifié(e) : Stephen23 le 14 Mai 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 commentaire
Sergio Rojas Blanco
Sergio Rojas Blanco le 15 Mai 2024
Thank you very much. it works perfectly and elegantly!
You answer everything :D

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Tags

Produits


Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by