matlab - Lowest starting row indices for minimum 2 consecutive non-zero values per column -


considering sample matrix:

a =      0     0     0     0    -4     3      0     2     1     0     0     0      0     5     0     8     7     0      0     9    10     3     1     2 

i want find lowest starting locations (row indices) each column of a minimum 2 consecutive non-zero values found. output this:

output = [0, 2, 0, 3, 3, 0] 

the 0's in output indicate condition of minimum 2 consecutive non-zero values doesn't stand.

also, generalized case of finding starting indices of minimum n consecutive non-zero values?

minimum 2 consecutive non-zero values case

%// mask of non-zeros in input, mask = a~=0  %// find starting row indices alongwith boolean valid flags minimum 2  %// consecutive nonzeros in each column [valid,idx] = max(mask(1:end-1,:) & mask(2:end,:),[],1)  %// use valid flags set invalid row indices zeros out = idx.*valid 

sample run -

a =      0     0     0     0    -4     3      0     2     1     0     0     0      0     5     0     8     7     0      0     9    10     3     1     2 mask =      0     0     0     0     1     1      0     1     1     0     0     0      0     1     0     1     1     0      0     1     1     1     1     1 valid =      0     1     0     1     1     0 idx =      1     2     1     3     3     1 out =      0     2     0     3     3     0 

generic case

for generic case of minimum n consecutive non-zeros case, can use 2d convolution kernel column vectors of n ones, -

mask = a~=0  %// mask of non-zeros in input,  %// find starting row indices alongwith boolean valid flags minimum n  %// consecutive nonzeros in each column [valid,idx] = max(conv2(double(mask),ones(n,1),'valid')==n,[],1)  %// use valid flags set invalid row indices zeros out = idx.*valid 

please note 2d convolution replaced separable convolution version mentioned in comments luis , seems bit faster. more info on accessed @ link. so,

conv2(double(mask),ones(n,1),'valid') replaced conv2(ones(n,1),1,double(mask),'valid').

sample run -

a =      0     0     0     0     0     3      0     2     1     0     1     2      0     5     0     8     7     9      0     9     0     3     1     2 mask =      0     0     0     0     0     1      0     1     1     0     1     1      0     1     0     1     1     1      0     1     0     1     1     1 n =      3 valid =      0     1     0     0     1     1 idx =      1     2     1     1     2     1 out =      0     2     0     0     2     1 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -