MATLAB Answers


Efficient method to detect nonzero value trains up to a certain lenght?

Asked by Erik
on 30 Jan 2019
Latest activity Commented on by Matt J
on 31 Jan 2019
I have data as follows (either numerical or logical, it doesn't matter in this case):
[0 1 0 1 1 0 1 1 1 0 1 1 1 1 0]
Every 0 represents one or more zeroes. I want to detect where consecutive sequences of ones are, but no longer than three after one another. I can do this imperatively with some for- or while-loop, walking over a window of five (?) elements, but I think that's computationally ineffective. How can I do this without loops, but with something like conv or movmean?
The expected (logical) result for trains of nonzero values up to three long is
[0 1 0 1 1 0 1 1 1 0 0 0 0 0 0]
I know I can detect single peaks with:
function tf = findsinglenonzeros(x)
c = conv(double(x), [1, 1, 1], 'same');
tf = c & x == c;
But now for of nonzero values up to three (or n) long.


Sign in to comment.

2 Answers

Answer by Matt J
on 30 Jan 2019
 Accepted Answer

P=find(~[0 x(:).' 0]);
locations=P( idx );
result =cumsum(z(1:end-1)),


I'm accepting this as it's quite an explicit and understandable (and tweakable, if needed) approach. And it doesn't rely on any toolboxes.
thanks, but be mindful that bwareaopen is probably faster

Sign in to comment.

Answer by Image Analyst
on 30 Jan 2019
Edited by Image Analyst
on 30 Jan 2019

If you have the Image Processing Toolbox, you can do it in one line of code with bwareaopen(), or bwareafilt() - the function meant for this:
% Create sample data
v = [0 1 0 1 1 0 1 1 1 0 1 1 1 1 0]
% Extract only runs of 3 or shorter.
output = v - bwareaopen(v, 4) % One way.
output = bwareafilt(logical(v), [1,3]) % Another way.


Brilliant answer, a very compact solution and nice to see that there are functions for this. The toolbox requirement is a small downside of this answer and the underlying algorithmic complexity is not transparent, but that's the case with any function.
Well I thought I'd give it a shot since the Image Processing Toolbox is their most commonly held toolbox I believe, and the bwareafilt() function does exactly what you asked.
True, it does it all in one line of code and hides whatever complex stuff it had to do inside, but I think that is preferable than trying to understand the code you accepted, and like you said, all functions are like that. You might want to think about getting the toolbox since it's useful for much more than just image processing.
Anyway, thanks for voting for the answer, and maybe it will help someone else who does have the toolbox.

Sign in to comment.