Repeated elements in an array

2 ビュー (過去 30 日間)
Rim Abdallah
Rim Abdallah 2022 年 5 月 4 日
コメント済み: Rim Abdallah 2022 年 5 月 4 日
if I have:
A=[3 7 25 27 30 31 32 34 35 36]
B=[2 4 2 2 2 0 3 2 3 2]
How can I have the index of the first element repeated in B and use it in A to have :
A=[3 7 25 31 32 34 35 36]
B=[2 4 2 0 3 2 3 2]
I used diff(B), but it will give:
A=[3 7 30 31 32 34 35 36]
B=[2 4 2 0 3 2 3 2]
(30 instead of 25, 30 represents the last element in B that has value of 2; or what I want is the first element in B that has value of 2 which is 25 in my case).
Is there any logic way or i should use a loop?

採用された回答

Stephen23
Stephen23 2022 年 5 月 4 日
編集済み: Stephen23 2022 年 5 月 4 日
A = [3 7 25 27 30 31 32 34 35 36];
B = [2 4 2 2 2 0 3 2 3 2];
Either define new variables:
X = [true,diff(B)~=0];
C = A(X)
C = 1×8
3 7 25 31 32 34 35 36
D = B(X)
D = 1×8
2 4 2 0 3 2 3 2
or if you really want to remove elements from A and B:
Y = [false,~diff(B)];
A(Y) = []
A = 1×8
3 7 25 31 32 34 35 36
B(Y) = []
B = 1×8
2 4 2 0 3 2 3 2
  1 件のコメント
Rim Abdallah
Rim Abdallah 2022 年 5 月 4 日
Thank you, it works!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by