Matlab查找连续零的数量

时间:2016-10-28 04:53:25

标签: matlab matrix series

我想在矩阵中找到系列零的长度

A = [0 0 0 3 1 4 6 0 9 1 0 0 0 0 0 0 1 5 2 1 1;2 3 1 0 0 4 6 0 0 0 2 3 8 6 0 0 0 0 0 1 1]

我需要结果给出zeroZeros = [3 1 6; 2 3 5]以及[row,cols]系列的零值 非常感谢你...

1 个答案:

答案 0 :(得分:1)

您可以按照以下方式执行此操作:

A = [0 0 0 3 1 4 6 0 9 1 0 0 0 0 0 0 1 5 2 1 1;
    2 3 1 0 0 4 6 0 0 0 2 3 8 6 0 0 0 0 0 1 1];


[N,~] = size(A);

% pad A==0 with zeros, and calculate diff for each row
A2 = diff([zeros(N,1) A==0 zeros(N,1)],[],2);

out_mtx = [];

for row_i = 1:size(A2,1)
    row = A2(row_i, :);
    zero_lengths = find(row == -1) - find(row == 1);
    out_mtx(end+1,:) = zero_lengths;
end

out_mtx

哪个给出了

out_mtx =

     3     1     6
     2     3     5