Change duplicate elements in an array with zero
Show older comments
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
Answers (2)
Walter Roberson
on 27 Apr 2018
A([false,A(1:end-1)==A(2:end)]) = 0;
6 Comments
Giorgio Proietti
on 27 Apr 2018
Walter Roberson
on 27 Apr 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
on 27 Apr 2018
Ameer Hamza
on 27 Apr 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
on 27 Apr 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
on 27 Apr 2018
Ameer Hamza
on 28 Apr 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 Comment
Giorgio Proietti
on 28 Apr 2018
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!