Position of the left nearest one value in a vector
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Rub Ron
am 12 Sep. 2019
Beantwortet: Stephen23
am 13 Sep. 2019
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 Kommentare
Akzeptierte Antwort
madhan ravi
am 12 Sep. 2019
Bearbeitet: madhan ravi
am 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 Kommentare
Weitere Antworten (2)
Bruno Luong
am 12 Sep. 2019
Bearbeitet: Bruno Luong
am 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 Kommentare
Stephen23
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!