I can write down the following Python code:

for j1 > 2:
    time1 = i1
for i2 > i1:
    if j2  < 2:
        time2 = i2

Purpose of the above code:

Consider a set of touples M = [(i1,j1),(i2,j2),(i3,j3),etc]

what I want to do is (because in my case i = time and j = some physical value) isolate the interval in which my physical value is above the value 2. I want to be able to say, at the end, that the physical value j is above 2 for exactly 2.5 seconds, for example.

I wrote in in python code above, does anyone know how to rewrite it in Mathematica code?

  • 1
    $\begingroup$ Can there be multiple intervals where j > 2? $\endgroup$ – Marius Ladegård Meyer Oct 5 '15 at 12:29
  • 1
    $\begingroup$ Why are you repeatedly setting time1=i1 when i1 is not being iterated over? $\endgroup$ – Patrick Stevens Oct 5 '15 at 12:32
  • $\begingroup$ Marius: no, there is only one interval. Patrick: because (i1,j1) are part of a tuple, so it makes sense to iterate over j1, but then i1 depends on the value of j1. In Mathematica this would be a table of pairs. $\endgroup$ – PhysNerd90 Oct 5 '15 at 12:36
  • 1
    $\begingroup$ I don't understand your Python code (did you mean if instead of for?), but Cases[list, {i_, j_} /; j > 2] selects those pairs where $j > 2$. Then sort by $i$ (SortBy) and take the first and last elements. $\endgroup$ – Szabolcs Oct 5 '15 at 12:38
  • $\begingroup$ Your question is unclear. Can you elaborate and maybe show a numerical example of what you mean. $\endgroup$ – Jack LaVigne Oct 5 '15 at 14:21

In Mathematica, there's no need to do this looping over indices. Say your data is a list of tuples ordered in time:

testdata = Table[{x, 5 - .1 (x - 7.)^2}, {x, 0, 15, .1}];

enter image description here

Now you just need to Select the portion which meets the criterion. Select[testdata, #[[2]] > 2 &] will return the tuples whose second value is greater than 2, and

Select[testdata, #[[2]] > 2 &][[{1, -1}, 1]]

(*  {1.6, 12.4}  *)

returns the first and last time points whose value was greater than 2.


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