How do I find non-zero values + lonely zeros in an array?

Hey, I would like to find the non-zero cells plus the zeros that has no zeros before or after them. For example in the array [0 1 2 2 2 0 0 4 5 0 3 0 0 0 5] I'll get the indexes: 1,2,3,4,5,8,9,10,11,15.
Thanks!

1 Comment

Explain how [0 1 2 2 2 0 0 4 5 0 3 0 0 0 5] gives indexes: 1,2,3,4,5,8,9,10,11,15.
At index 1, there is a 0, but at index 2 there is a non-zero.
Explain exactly what "plus" means in "find the non-zero cells plus the zeros " Does plus mean plus, like in "+" as in addition? Or does it mean like "also" or a logical AND?
I could see if you just wanted a list of non-zero values, like find(v~=0), but you are not giving that as your desired output.
You give 2 as one of the indexes, yet the 1 at index 2 has a zero before it and you specifically said "has no zeros before or after them" so why is 2 one of the indexes when it DOES have a zero before it (at index 1)???

Sign in to comment.

 Accepted Answer

v = [0 1 2 2 2 0 0 4 5 0 3 0 0 0 5];
union(strfind([false, v == 0, false], [0 1 0]), find(v))

3 Comments

Thank you. and if I want to add another condition? for example the numbers should be bigger than x?
Not sure if the 0s should be included since it's not going to be greater than positive x but in any case, finding numbers greater than a value is trivial:
find(v > x)
You can put that instead of the find(v) in the above expression if you also want the 0s after a non-zero.

Sign in to comment.

More Answers (1)

Try this:
v = [0 1 2 2 2 0 0 4 5 0 3 0 0 0 5];
x = 2 % Threshold.
% Find v > x
% Find locations where v > x.
moreThanX = v > x
% Find zeros of length exactly 1 (is that what defines a "lonely" zero?????)
% First find location of all zeros:
allZeros = v == 0
% Now get only the regions with area = 1;
singleZeros = allZeros & ~bwareaopen(allZeros, 2)
% Combine that single zeros mask with the v>x mask to get all locations.
overallMask = singleZeros | moreThanX
% Turn logical vector into actual indexes.
out = find(overallMask)

Categories

Asked:

on 15 Dec 2017

Commented:

on 17 Dec 2017

Community Treasure Hunt

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

Start Hunting!