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

1 view (last 30 days)
Paul Hoffrichter on 19 Jun 2022
Answered: Jan on 19 Jun 2022
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?

Jan on 19 Jun 2022
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.

R2020a

### Community Treasure Hunt

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

Start Hunting!

Translated by