Repeated elements in an array

2 Ansichten (letzte 30 Tage)
Rim Abdallah
Rim Abdallah am 4 Mai 2022
Kommentiert: Rim Abdallah am 4 Mai 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?

Akzeptierte Antwort

Stephen23
Stephen23 am 4 Mai 2022
Bearbeitet: Stephen23 am 4 Mai 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

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by