matlab - How to count non zero elements in a vector and replace this values based the number of occurences -
this question has answer here:
- finding islands of zeros in sequence 7 answers
i'm new matlab user , in case have vector let say:
v = [0 0 0 0.1 0.2 0.3 0.4 0.5 0 0 0 0 0 0 0.1 0.2]
i want count consecutive non 0 values i.e in vector have first 5 nonzero values [0.1 0.2 0.3 0.4 0.5]
, 2 last nozeros values [0.1 0.2]
what want is: count consecutive non 0 values , put condition i.e. if length of nonzeros greater 3 (count>3
) respective values of vector v(i) remain v(i) if length consecutive values less 3 (count<3
) respective values of v(i) = 0
i want new vector let v1 derivated vector v where:
v1 = [0 0 0 0.1 0.2 0.3 0.4 0.5 0 0 0 0 0 0 0 0]
any appreciated.
if have matlab image processing toolbox, can use power of morphological operations. morphological opening (imopen
) removes objects smaller structuring element image. can use in 2d , use [1,1,1]
structuring element remove objects, i.e. sequences of nonzero elements, shorter 3:
first make sequence binary: 0 or nonzero.
w = v~=0;
then zero-pad sequence, short nonzero sequences @ borders eliminated. use [1,1,1]
structuring element, zero-padding 1 sufficient:
w = [0,w,0];
now opening remove small nonzero sequences
w1 = imopen(w, [1,1,1]);
the vector w1
contains 0
if corresponding element in v
or should set 0
, 1
if value should kept. result v1
, can ignore first , last entry (those elements zero-padding), , multiply input, e.g. 1 * 0.1 = 0.1
:
v1 = w1(2:end-1) .* v;
which gives correct result without loop, if statement or such stuff! 4 simple operations: morphology , bit of multiplication , zero-padding.
Comments
Post a Comment