Find a series of consecutive numbers and change index of them

1 回表示 (過去 30 日間)
Jaehwi Bong
Jaehwi Bong 2019 年 8 月 12 日
回答済み: Andrei Bobrov 2019 年 8 月 12 日
Hi,
I have this kind of data. The first column and second column of the data refers to Index and time series(not consecutive) relatively.
Data = [1 1; 1 2; 1 3; 1 5; 1 6; 1 10; 1 11; 1 13; 1 20; 1 21; 1 22;];
I'd like to change this index number using Matlab code(to apply to thousands of data) when the value of the second colmn is not consecutive numbers.
So in my example, the first column should be changed [1; 1; 1; 2; 2; 3; 3; 4; 5; 5; 5;] .
If anyone can help, it would be greatly appreciated.
Thank you!

採用された回答

the cyclist
the cyclist 2019 年 8 月 12 日
編集済み: the cyclist 2019 年 8 月 12 日
Data(:,1) = cumsum(diff([Data(1,2); Data(:,2)]) ~= 1);
will change the first column to what you want.
That's might be a bit "obfuscated" for you, but it is pretty straightforward to parse what is going on.
[Data(1,2); Data(:,2)]
is appending another copy of the first element at the front of the vector. I do that so that the first element of your vector will look non-consecutive to the "prior" one, and therefore be assigned index 1.
diff() ~= 1
is identifying the locations with non-consecutive jumps, putting a 1 there.
cumsum()
takes the cumulative sum along the vector, which means that each time a 1 is encountered, your index is incremented.

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2019 年 8 月 12 日
[~,~,Data(:,1)] = unique(cumsum(Data(:,1)) - Data(:,2),'stable');

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by