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!