Azzera filtri
Azzera filtri

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

27 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Stephen23
Stephen23 il 14 Set 2020
Modificato: Stephen23 il 14 Set 2020
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

Più risposte (0)

Categorie

Scopri di più su Tables in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by