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

25 vues (au cours des 30 derniers jours)
Centauri Jolene
Centauri Jolene le 14 Sep 2020
Commenté : Centauri Jolene le 14 Sep 2020
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.

Réponse acceptée

Stephen23
Stephen23 le 14 Sep 2020
Modifié(e) : Stephen23 le 14 Sep 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
  1 commentaire
Centauri Jolene
Centauri Jolene le 14 Sep 2020
Worked perfectly and makes perfect sense, thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by