MATLAB: How to find indices that fulfil a certain criteria

locate indices

Lets say I want to write a script and the input is the following vector:
vector = [1 1 1 1 3 3 3 9 9 9 9 2 2 1 1 1 2 7 9 7 2 1 1 1]
I want the result to be a new vector that contain the indices [12 21] (the two 2's in bold and italic). The script should chose these indices because they are the first to follow index 7 and 17 (in bold) and at the same time have a value of that particular index +/- one… I hope it make sense and that it is doable. Thanks Michael

Best Answer

after_7 = 1:numel(vector) > 7;
after_17= 1:numel(vector) > 17;
twos_after_7 = vector == 2 & after_7;
twos_after_17 = vector == 2 & after_17;
output = find(twos_after_7,1,'first');
output(2) = find(twos_after_17,1,'first');