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!