How to zero out short non-zero regions in vector?

조회 수: 1 (최근 30일)
Paul Hoffrichter
Paul Hoffrichter 2022년 6월 19일
답변: Jan 2022년 6월 19일
For a minLength integer input value, zero out short non-zero regions.
The input vector, A, typically will have long regions of 0's instead of 1, 2, or 3 zero length regions in my example.
If minLength = 3, then I want the [0 4 5 0] region to be 0's. Y is the output:
A = [4 5 6 5 0 0 5 6 2 0 3 4 6 7 8 0 4 5 0 0 0 7 2 1 9 9 0]; % Input
Y = [4 5 6 5 0 0 5 6 2 0 3 4 6 7 8 0 0 0 0 0 0 7 2 1 9 9 0]; % minLength = 3
Y = [4 5 6 5 0 0 0 0 0 0 3 4 6 7 8 0 0 0 0 0 0 7 2 1 9 9 0]; % minLength = 4
I tried starting with:
Alog = logical( [0 A 0] )
AzerIdx = find( Alog == 0 );
AzerIdxDif = diff(AzerIdx) - 1; % This gives me the number of non-zero's in each non-zero region.
and wasn't sure how to get the desired output Y for a given integer value of minLength.
Also, with long regions of zeros, I get many 1's that I am not interested in, since no need to change a 0 to a 0.
Is this the right approach or is there a more efficient way to do this? How to get the output Y?

답변 (1개)

Jan
Jan 2022년 6월 19일
A = [4 5 6 5 0 0 5 6 2 0 3 4 6 7 8 0 4 5 0 0 0 7 2 1 9 9 0];
minLen = 3;
[b, n] = RunLength(A == 0);
b(n < minLen) = true;
M = RunLength(b, n);
A(M) = 0;
If you do not have a C-compiler to create the fast C-Mex, use RunLength_M, which is included in the same submission.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by