Clear Filters
Clear Filters

Find min and max in groups

6 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 14 May 2024
Edited: Stephen23 on 14 May 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 Comment
Sergio Rojas Blanco
Sergio Rojas Blanco on 15 May 2024
Thank you very much. it works perfectly and elegantly!
You answer everything :D

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!