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

1 次查看(过去 30 天)
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;
end
But now for of nonzero values up to three (or n) long.

采纳的回答

Matt J
Matt J 2019-1-30
n=3;
P=find(~[0 x(:).' 0]);
d=diff(P)-1;
idx=(d>=1)&(d<=n);
locations=P( idx );
lengths=d(idx);
z=zeros(1,numel(x)+1);
z(locations)=1;
z(locations+lengths)=-1;
result =cumsum(z(1:end-1)),
  2 个评论
Erik
Erik 2019-1-30
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.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2019-1-30
编辑:Image Analyst 2019-1-30
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.
  2 个评论
Erik
Erik 2019-1-30
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.
Image Analyst
Image Analyst 2019-1-31
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Linear Prediction 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by