Change duplicate elements in an array with zero
显示 更早的评论
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
回答(2 个)
Walter Roberson
2018-4-27
A([false,A(1:end-1)==A(2:end)]) = 0;
6 个评论
Giorgio Proietti
2018-4-27
Walter Roberson
2018-4-27
[~, ~, 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
2018-4-27
Ameer Hamza
2018-4-27
@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
2018-4-27
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
2018-4-27
Ameer Hamza
2018-4-28
@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_;
类别
在 帮助中心 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!