Given an array sel
and an index position i0
, how can I find the position of the nearest (left or right) nonzero element?
I'm able to do it with a loop and a couple of awful If's, but I was looking for a functional way...
lr=Length[sel];
For[i = 0, i <= lr, i++,
If[1 <= i0 + i <= lr && sel[[i0 + i]] == 1, Print[i0+i]; Break[],
If[1 <= i0 - i <= lr && sel[[i0 - i]] == 1, Print[i0-i];Break[]]]]
Nearest
if you'd like. Also, take a look atLengthWhile
... it does what your loop does in one go. $\endgroup$ – ciao Apr 22 '15 at 22:20