フィルターのクリア

Find min and max in groups

6 ビュー (過去 30 日間)
Sergio Rojas Blanco
Sergio Rojas Blanco 2024 年 5 月 14 日
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

採用された回答

Stephen23
Stephen23 2024 年 5 月 14 日
編集済み: Stephen23 2024 年 5 月 14 日
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 件のコメント
Sergio Rojas Blanco
Sergio Rojas Blanco 2024 年 5 月 15 日
Thank you very much. it works perfectly and elegantly!
You answer everything :D

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by