Position of the left nearest one value in a vector

조회 수: 3 (최근 30일)
Rub Ron
Rub Ron 2019년 9월 12일
답변: Stephen23 2019년 9월 13일
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에서 Simscape Electrical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by