Position of the left nearest one value in a vector

1 次查看(过去 30 天)
I have a vector of ones and zeros of this form: v = [0 0 1 0 0 0 1 1 1 1 0 0 1 1 0 0 0 0 0 1 0];
how can I get a vector with the left nearest zero from the one values, so that the output x is:
v = [0 0 1 0 0 0 1 1 1 1 0 0 1 1 1 0 0 1 0];
x = [0 0 2 0 0 0 6 6 6 6 0 0 12 12 12 0 0 17 0];
I am shamelly blocked so any hint to at least how to begin with would be very much appreciated.

采纳的回答

madhan ravi
madhan ravi 2019-9-12
编辑:madhan ravi 2019-9-12
I don't know what you mean by shamely blocked.
It's not a trivial one though.
x=v;
Start=strfind([0,v==1],[0,1]);
End=strfind([v==1,0],[1,0]);
x(v==1)=repelem(Start-1,diff([Start;End+1]))

更多回答(2 个)

Bruno Luong
Bruno Luong 2019-9-12
编辑:Bruno Luong 2019-9-13
v = [0 0 1 0 0 0 1 1 1 1 0 0 1 1 1 0 0 1 0] % requirement: it must start with 0
Method 1
i0=find(v==0);
i1=find(v==1);
[~,loc]=histc(i1, [i0 Inf]);
v(i1)=i0(loc)
Method 2 (work with recent MATLAB versions)
i0=find(v==0);
i1=find(v==1);
v(i1)=interp1(i0,i0,i1,'previous')

Stephen23
Stephen23 2019-9-13
>> v = [0,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,0,1,0]
v =
0 0 1 0 0 0 1 1 1 1 0 0 1 1 1 0 0 1 0
>> d = diff([v,0])>0;
>> f = [0,find(d)];
>> x = f(1+v.*cumsum(d))
x =
0 0 2 0 0 0 6 6 6 6 0 0 12 12 12 0 0 17 0

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by