the first time there is zero before and after a particular index

4 views (last 30 days)
Hi All, I have a matrix which looks like this:
1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 Let's say that I want to find out at what indices there is the first zero happening before and after index 20. How do we do this? So, in my example here, my points of interest will be: 7 (for before) and 37 (for after).
Thanks

Accepted Answer

the cyclist
the cyclist on 30 Jul 2017
Here is one straightforward way:
x = [1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0];
anchor = 20;
positionIndex = 1:numel(x);
lastPriorZero = max(find(x==0 & positionIndex<anchor))
firstLaterZero = min(find(x==0 & positionIndex>anchor))

More Answers (1)

Image Analyst
Image Analyst on 30 Jul 2017
If you want to find the 0's just outside the 1's, and you have the Image Processing Toolbox, you can do this:
x = [1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0]
dilatedx = imdilate(x, [1,1,1]) % Grow 1 regions outward
indexes = find(dilatedx ~= x) % Find locations of mismatches.
and you get
indexes =
4 7 37
as you should.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!