Replace all zeros in vector by previous non-zero value

后端 未结 6 1311
孤独总比滥情好
孤独总比滥情好 2020-12-09 16:31

Matlab/Octave algorithm example:

 input vector: [ 1 0 2 0 7 7 7 0 5 0 0 0 9 ]
output vector: [ 1 1 2 2 7 7 7 7 5 5 5 5 9 ]

The algorithm is

6条回答
  •  旧巷少年郎
    2020-12-09 16:36

    I think is a vectorized solution. Works on your example:

    V = [1 0 2 0 7 7 7 0 5 0 0 0 9]
    %// This is where the numbers you will repeat lie. You have to cast to a double otherwise later when you try assign numbers to it it caps them at logical 1s
    d = double(diff([0,V])>0)
    %// find(diff([0,~V])==-1) - find(diff([0,~V])==1) is the length of each zero cluster
    d(find(d(2:end))+1) = find(diff([0,~V])==-1) - find(diff([0,~V])==1)
    %// ~~V is the same as V ~= 0
    V(cumsum(~~V+d)-1)
    

提交回复
热议问题