# Find min and max in groups

6 Ansichten (letzte 30 Tage)
Sergio Rojas Blanco am 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
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Stephen23 am 14 Mai 2024
Bearbeitet: Stephen23 am 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 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Sergio Rojas Blanco am 15 Mai 2024
Thank you very much. it works perfectly and elegantly!
You answer everything :D

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

R2024a

### Community Treasure Hunt

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

Start Hunting!

Translated by