How do I find non-zero values + lonely zeros in an array?
Show older comments
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
Image Analyst
on 16 Dec 2017
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)???
Accepted Answer
More Answers (1)
Image Analyst
on 16 Dec 2017
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
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!