Change duplicate elements in an array with zero
Mostrar comentarios más antiguos
hi, i have an array look like:
A = [1 1 0 0 -1 - 1 - 1 0 1 1 -1 ];
how can i turn it into:
A = [1 0 0 0 -1 0 0 0 1 0 -1];
Thanks
Respuestas (2)
Walter Roberson
el 27 de Abr. de 2018
A([false,A(1:end-1)==A(2:end)]) = 0;
6 comentarios
Giorgio Proietti
el 27 de Abr. de 2018
Walter Roberson
el 27 de Abr. de 2018
[~, ~, uidx] = unique(A);
A([false, uidx(1:end-1)==uidx(2:end)]) = 0;
So you can do it -- it is just a waste of time to do so.
Giorgio Proietti
el 27 de Abr. de 2018
Ameer Hamza
el 27 de Abr. de 2018
@Giorgio, your hand-written B vector is wrong. @Walter's code is giving correct output. Below is correct B
B = [0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1];
Walter Roberson
el 27 de Abr. de 2018
I think there is a consistent interpretation: that a non-zero entry is to be zeroed out if it is the same as the most recent non-zero entry.
Giorgio Proietti
el 27 de Abr. de 2018
Ameer Hamza
el 28 de Abr. de 2018
@Giorgio as you mentioned in your comment, the new information change which you mentioned in your question. The question can now be interpreted as only retain first non-zero entry after a sign change. The following code will work for you
index = A==0;
A_ = A(~index);
A_ = [A_(1) diff(A_)/2];
A(~index) = A_;
1 comentario
Giorgio Proietti
el 28 de Abr. de 2018
Categorías
Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!