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!