1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

5

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
Doresoom
  • 7,398
  • 14
  • 47
  • 61
Eitan T
  • 32,660
  • 14
  • 72
  • 109
2

The strfind method that @EitanT suggested is quite nice. Another way to do this is to use find and element-wise bit operations:

% let A be a logical ROW array
B = ~A & [A(2:end),false] & [false,A(1:end-1)];
elements = find(B);

This assumes, based on your example, that you want to exclude boundary elements. The concatenations [A(2:end),false] and [false,A(1:end-1)] are required to keep the array length the same. If memory is a concern, these can be eliminated:

% NB: this will work for both ROW and COLUMN vectors
B = ~A(2:end-1) & A(3:end) & A(1:end-2);
elements = 1 + find(B);  % need the 1+ because we cut off the first element above
sfstewman
  • 5,589
  • 1
  • 19
  • 26
0

...and to elaborate on @Eitan T 's answer, you can use strfind for an array if you loop by row

% let x = some matrix of 1's and 0's (any size)
[m n] = size(x);
for r = 1:m;
  pos(r,:) = strfind(x(r,:)',[1 0 1]) + 1;
end

pos would be a m x ? matrix with m rows and any returned positions. If there were no zeros in the proper positions though, you might get a NaN ... or an error. Didn't get a chance to test.

endowdly
  • 119
  • 1
  • 9