Repeated elements in an array

2 visualizaciones (últimos 30 días)
Rim Abdallah
Rim Abdallah el 4 de Mayo de 2022
Comentada: Rim Abdallah el 4 de Mayo de 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?

Respuesta aceptada

Stephen23
Stephen23 el 4 de Mayo de 2022
Editada: Stephen23 el 4 de Mayo de 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

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by