2
$\begingroup$

I have a really simple question but, sorry, I can't seem to find an elegant solution to other than iterating through. I have a list of indices, and a relative list of values, I would like to extract lists of intervals that contain the value 1.

For example say, IndexList = {1,5,10,12} Data = {0,1,1,0,0,0,0,0,0,0,1,0}

What I would like to get is {{1,5},{10,12}} or the intervals within the previous list that contained 1.

NOTE: For clarification, I am looking for all those intervals in which the relative list contains 1. The backstory is this is to try filtering data from a time series to extract positive examples to feed them to ML.

$\endgroup$
1
  • $\begingroup$ How do you expect an outcome to occur when you have only one 1? I would think from your initial explanation you'd want only a single value in the list? Or is it that you would be searching such that it goes "Is there a value 1 between 1,5? 5,10? 10,12?" $\endgroup$ Commented Jun 10, 2020 at 21:23

2 Answers 2

2
$\begingroup$

Maybe

Split[IndexList, Total[Data[[# ;; #2]]] >= 1 &]
{{1, 5}, {10, 12}}

Also

Split[IndexList, MemberQ[Data[[# ;; #2]], 1] &]
{{1, 5}, {10, 12}}
$\endgroup$
1
  • $\begingroup$ Actually, this is trickier than I expected. To get pairwise groupings to work right you need a function that evaluates differently across the pairs. In practice, I've found this doesn't work with more general lists of 0 and 1 data. If there were many 1's in the data field the output will be just a list of all the indeces separate. $\endgroup$ Commented Jun 10, 2020 at 13:49
2
$\begingroup$

With help from Kglr's answer, I worked out what I was looking for.

For the computation to work with arbitrary sequence of 0 and 1's I found I needed to explicitly identify all pairs of indices.

I am sure this is not the most elegant or concise, but it seems to work.

IndexList  = {1, 5, 10, 12};
Data = {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0};
ValidRanges = MemberQ[Data[ [#[[1]] ;; #[[2]]] ], 1.] & /@ 
 Partition[Sort[Join[IndexList, IndexList]][[2 ;; -1 ]], 2]
ValidData = Data[ [#[[1]] ;; #[[2]]] ] & /@ 
 Partition[Sort[Join[IndexList, IndexList]][[2 ;; -1 ]], 2]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.