from a column in a table, get row indices where value changes
18 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Stephen23
2020-9-14
编辑:Stephen23
2020-9-14
>> 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
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!