Repeated elements in an array

2 views (last 30 days)
Rim Abdallah
Rim Abdallah on 4 May 2022
Commented: Rim Abdallah on 4 May 2022
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?

Accepted Answer

Stephen23
Stephen23 on 4 May 2022
Edited: Stephen23 on 4 May 2022
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

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!