# How to calculate time steps from a time series

(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)

Suppose you have a time series. For example, you've tracked your health really well and noted when you come down with a cold; you want to know the average time you tend to go without a cold. Or, you've got measurement data from a Geiger-counter that clicks whenever it detects a particle, and you want to characterize the distribution of times between events.

If you were to tackle this problem like a C programmer, you'd probably try something like this, which works but is not the PDL way:

``` \$time_series = when_I_get_colds();
\$gone_without = zeroes(\$time_series->nelem - 1);
for(\$i = 0; \$i < \$gone_without->nelem; \$i++) {
\$gone_without(\$i) .= \$time_series(\$i + 1) - \$time_series(\$i);
}
print "I usually go ", \$gone_without->avg, " days without a cold.\n";
```

Don't do that. Instead, here's the easy PDL way to analyze your cold data:

``` \$time_series = when_I_get_colds();
\$start_times = \$time_series(0:-2);
\$next_times = \$time_series(1:-1);
\$gone_without = \$next_times - \$start_times;
print "I usually go ", \$gone_without->avg, " days without a cold.\n";
```

You could write that even more compactly by not even assigning the start and next times to variables. Here's an analysis of the Geiger-counter data:

``` \$time_series = load_detection_times();
\$deltas = \$time_series(1:-1) - \$time_series(0:-2);
analyze_time_distr(\$deltas);
```

Note - I assume you've `use`d NiceSlice in all of these.

To do: discuss using Inline::Pdlpp