Position of the left nearest one value in a vector
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
madhan ravi
on 12 Sep 2019
Edited: madhan ravi
on 12 Sep 2019
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]))
0 Comments
More Answers (2)
Bruno Luong
on 12 Sep 2019
Edited: Bruno Luong
on 13 Sep 2019
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')
0 Comments
Stephen23
on 13 Sep 2019
>> 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
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!