10

4

I'd like to find the points of a time-series that are a certain distance away (in value, not in time) from the previous maximum, which I consider a reversal.

For example, for `{1, 2, 3, 5, 10, 8, 6, 3}`

with a threshold of `4`

, the reversal point would be `6`

, since it's `4`

units away from the previous maximum of `10`

.

I want to find all such reversal points, but at each one I need to reset the running maximum (or split the list and start again on the new list).

Here is some code to find the first reversal. It computes the distance from each element to a rolling maximum, then looks for the first difference bigger than the threshold.

```
ts = {1, 2, 3, 5, 10, 8, 6, 3};
rollmax = FoldList[Max, First[ts], Rest[ts]];
delta = rollmax - ts;
sel = Map[# >= 4 &, delta];
index = Position[sel, True, 1, 1]
```

I can do this in a procedural way, but it's probably not the preferred way. I'm new to functional programming and I don't quite know what sort of patterns are available that would help me here.

And if there was a better way of writing the above code, please let me know.

BTW, if you need to get the parts indexed by Position look to

`Extract`

; but I suspect if you are already programming with`FoldList`

you know of this. – Mr.Wizard – 2012-02-14T19:21:27.363The only func programming I knew was map/reduce/filter and the x:xs concept from Haskell. I found

`FoldList`

when searching for something suitable in the Virtual Book. BTW, my first version looked like this`FoldList[Max, 0, ts][[2;;]]`

, but then I remembered x:xs – Meh – 2012-02-15T01:44:12.660@Adal that is an interesting avenue to

Mathematica; some day I should learn Haskell. I argue that`FoldList`

as you started with is superior to the answer you presently have selected. See my updated answer for comparative timings. – Mr.Wizard – 2012-02-15T09:33:09.400