配列要素内の最大値だけを抽出する方法

ZZ =
1 10
1 13
2 13
1 14
2 14
3 14
3 15
3 16
2 17
2 18
上記の配列で,
以下のように2列目の値が同じ値の中で,1列目の値が最大の行だけ抽出する方法を教えてください.
尚,ループなしの方法でお願いいたします.
ans =
1 10
2 13
3 14
3 15
3 16
2 17
2 18

 Akzeptierte Antwort

Hernia Baby
Hernia Baby am 25 Apr. 2021

0 Stimmen

ZZのような行列であること前提で話します。
前提
  1. 2列目のデータが連続で並んでいる 
  2. 1列目のデータが昇順になっている
やりかた
 2列目にunique関数を設けて、最後の行のみを抽出します。
 そしてidxに当てはまる行を抽出します。
[c,idx] = unique(ZZ(:,2),'last');
ZZ(idx,:)
ans =
1 10
2 13
3 14
3 15
3 16
2 17
2 18
ーーーーーーーーーーーー
unique関数についてはこちら

1 Kommentar

Akira Agata
Akira Agata am 26 Apr. 2021
配列ZZが、@Hernia Baby さんの指摘されたような前提を満たさない場合は、findgroups と splitapply 関数を組み合わせることで実現可能です。
[group, gID] = findgroups(ZZ(:,2));
maxVal = splitapply(@max,ZZ(:,1),group);
result = [maxVal, gID];
>> result
result =
1 10
2 13
3 14
3 15
3 16
2 17
2 18

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!