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에서 Linear Prediction에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!