Changing duplicates in an array to zero?

6 ビュー (過去 30 日間)
Dominic Green
Dominic Green 2014 年 3 月 25 日
回答済み: Jos (10584) 2014 年 3 月 25 日
SO I have an array that looks like:
0 0 6 6 3 3
Basically my question is, how do you check for a duplicate value and if there is a duplicate existing, keep the first value, but set the second value to zero.
The result would be:
0 0 6 0 3 0
Thanks in advance, Dom
  2 件のコメント
Joseph Cheng
Joseph Cheng 2014 年 3 月 25 日
Are you just talking about consecutive duplicate values? such as [0 0 6 6 3 3 6 6 3 3] turns to [ 0 0 6 0 3 0 6 0 3 0]
or all duplicate values? such as [ 0 0 6 3 6 3] becomes [0 0 6 3 0 0].
Dominic Green
Dominic Green 2014 年 3 月 25 日
The second one,

サインインしてコメントする。

採用された回答

Joseph Cheng
Joseph Cheng 2014 年 3 月 25 日
編集済み: Joseph Cheng 2014 年 3 月 25 日
here is a simple thing i just threw together. Hopefully it helps. As you can see what i'm doing below is finding the differences using diff() which subtracts adjacent values. when offset by x(1) and you can see that the zero values in y line up with the duplicate values found in x. using the find function you can get the index of zero values when y is zero. then you can substitute the values (here i used z) for zero.
x = [1 1 6 6 3 3 2 3 4 6 6 3 3 2 2 2 3 3 3]
y = [ x(1) diff(x)]
y = find(y==0);
z = x
z(y)=0
if it is all duplicate values as i asked in my earlier comment. Still thinking about that one.
  3 件のコメント
Dominic Green
Dominic Green 2014 年 3 月 25 日
But I like your thinking, I just made myself one. Thanks a heap!
Joseph Cheng
Joseph Cheng 2014 年 3 月 25 日
simpler way, you can also use [C,IA,IC] = unique(x,'stable')and it'll give you the index of the first occurrence in IA for that number. and then you can set the rest into 0

サインインしてコメントする。

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 3 月 25 日
x = [1 1 6 6 3 3 2 3 4 6 6 3 3 2 2 2 3 3 3]
y = zeros(size(x))
[~,i] = unique(x,'first')
y(i) = x(i)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by