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

8 views (last 30 days)
翔 池田
翔 池田 on 25 Apr 2021
Commented: Akira Agata on 26 Apr 2021
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

Accepted Answer

Hernia Baby
Hernia Baby on 25 Apr 2021
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 Comment
Akira Agata
Akira Agata on 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

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!