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.
0 个评论
采纳的回答
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 个评论
更多回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Get Started with DSP System Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!