Search code examples
arraysalgorithmmatlabmatrix-indexing

Effective picking of surrounded element


If I have sequence 1 0 0 0 1 0 1 0 1 1 1 how to effectively locate zero which has from both sides 1.

In this sequence it means zero on position 6 and 8. The ones in bold.

1 0 0 0 1 0 1 0 1 1 1

I can imagine algorithm that would loop through the array and look one in back and one in front I guess that means O(n) so probably there is not any more smooth one.

If you can find another way, I am interested.


Solution

  • Use strfind:

    pos = strfind(X(:)', [1 0 1]) + 1
    

    Note that this will work only when X is a vector.

    Example

    X = [1 0 0 0 1 0 1 0 1 1 1 ];
    pos = strfind(X(:)', [1 0 1]) + 1
    

    The result:

    pos =
         6     8