每列最少2个连续非零值的最低起始行索引

时间:2015-06-01 09:30:15

标签: matlab 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

我想找到A每列的最低起始位置(行索引),其中找到最少2个连续的非零值。输出看起来像这样:

Output = [0, 2, 0, 3, 3, 0]

输出中的0表示minimum 2 consecutive non-zero values的条件并不存在。

另外,这可以推广到找到最小N个连续非零值的起始指数的情况吗?

1 个答案:

答案 0 :(得分:4)

最少2个连续的非零值案例

%// Mask of non-zeros in input, A
mask = A~=0

%// Find starting row indices alongwith boolean valid flags for minimum two 
%// consecutive nonzeros in each column
[valid,idx] = max(mask(1:end-1,:) & mask(2:end,:),[],1)

%// Use the valid flags to set invalid row indices to zeros
out = idx.*valid

示例运行 -

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

通用案例

对于最小N个连续非零情况的一般情况,您可以将2D convolution与内核一起用作N个列的向量,如下所示 -

mask = A~=0  %// Mask of non-zeros in input, A

%// Find starting row indices alongwith boolean valid flags for minimum N 
%// consecutive nonzeros in each column
[valid,idx] = max(conv2(double(mask),ones(N,1),'valid')==N,[],1)

%// Use the valid flags to set invalid row indices to zeros
out = idx.*valid

请注意,2D卷积可以替换为Luis评论中提到的可分离卷积版本,并且似乎更快一些。有关这方面的更多信息,请访问此link。所以,

conv2(double(mask),ones(N,1),'valid')可以替换为conv2(ones(N,1),1,double(mask),'valid')

示例运行 -

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