I wonder if someone has a more efficient solution to the following:
I have a time-series (sample below):
signal = [0 1 4 8 11 7 14 25 22 18 14 9 3 -2 -5 -11 -15 -9 -3 5 6]';
And I am trying to create a stepping algorithm that measures when certain thresholds are "crossed". So for example, the "response" output would start at zero and increment at each 5-unit band. Starting at zero, the thresholds would be -5 and 5. Suppose the signal crosses 5, then the current "response" would be 5, and the new thresholds 0 and 10, etc.
band = 5;
initial = 0;
response = zeros(length(signal),1);
response(1) = initial;
I created the following for-loop below which does the job pretty well.
for idx = 2 : length(signal)
upTrigger = response(idx-1) + band;
downTrigger = response(idx-1) - band;
if signal(idx) > upTrigger
response(idx) = upTrigger;
elseif signal(idx) < downTrigger
response(idx) = downTrigger;
response(idx) = response(idx-1);
If you plot (stairs) the signal and response vectors together, you will notice the following two things:
1. Even if the signal overshoots one of the thresholds, the new value for "response" takes that threshold, not the current signal value.
2. The response value can change by only 1 x band at a time, even if the signal jumps hugely. You can observe this in a few places on the graph.
These two behaviors are desired.
I wonder if someone has a (much) more efficient (vectorized? Use of "floor / ceil"?) solution to generating the "response" vector than a for-loop.