Position of the left nearest one value in a vector

3 vues (au cours des 30 derniers jours)
Rub Ron
Rub Ron le 12 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.

Réponse acceptée

madhan ravi
madhan ravi le 12 Sep 2019
Modifié(e) : madhan ravi le 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]))

Plus de réponses (2)

Bruno Luong
Bruno Luong le 12 Sep 2019
Modifié(e) : Bruno Luong le 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')

Stephen23
Stephen23 le 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

Catégories

En savoir plus sur Simscape Electrical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by