フィルターのクリア

from a column in a table, get row indices where value changes

16 ビュー (過去 30 日間)
Centauri Jolene
Centauri Jolene 2020 年 9 月 14 日
コメント済み: Centauri Jolene 2020 年 9 月 14 日
I have a table with a column of 0s and 1s and I need to get the row indices where the value changes.
Essentially, I need the row indicies corresponding to the sets/sequences of 1s.
For exmaple, in this data, I would need row indicies 2, 4 and 8, 10.
0
1
1
1
0
0
0
1
1
1
0
0
I atatched an example dataset (as a table) with the column called 'B' which has the 0s and 1s.
I tried the following codes:
yIdx = find(data.Y, 1); % only returns the first instance of 1
[~, yIdx] = ismember(1, data.Y); % only returns the first instance of 1
index = any(data.Y == 1, 2), %returns a vector of logicals
test = find(any(data.Y == 1, 2)); % this gives me all the row indices for all instances of 1. I need just the indices where a sequence of 1s starts and ends.

採用された回答

Stephen23
Stephen23 2020 年 9 月 14 日
編集済み: Stephen23 2020 年 9 月 14 日
The trick is to use diff, e.g. with the example data from your question:
>> Y = [0;1;1;1;0;0;0;1;1;1;0;0];
>> D = diff([0;Y;0]);
>> S = find(D>0) % start of each run of ones
S =
2
8
>> E = find(D<0)-1 % end of each run of ones
E =
4
10
For the uploaded table's column Y this gives:
>> D = diff([0;data.Y;0]);
>> S = find(D>0) % start of each run of ones
S =
99
149
5481
6073
>> E = find(D<0)-1 % end of each run of ones
E =
105
157
5538
6076
  1 件のコメント
Centauri Jolene
Centauri Jolene 2020 年 9 月 14 日
Worked perfectly and makes perfect sense, thank you!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTables についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by