matlab - finding indeces of similar group elements -
i have vector test2
includes nan 0
, 1
in random order (we cannot make assumption).
test2 = [nan 1 1 1 0 0 0 nan nan nan 0 0 0 1 1 1 0 1 1 1 ];
i group elements containing consecutive 1
, have in separte vectors start
, finish
first , last index of groups.
in case start
, finish
should be:
start = [2 14 18]; finish = [4 16 20];
i tried adapt code provided here coming solution not working...could me right solution , tell me why 1 tried doesn't work?
a = (test2 ==1); d = diff(a); start = find([a(1) d]==1); % start index of each group finish = find([d - a(end)]==-1); % last index of each group start = 2 14 18 finish = 2 3 5 6 7 8 9 10 11 12 14 15 18 19
i using matlab r2013b running on windows. tried using matlab r2013a running on ubuntu.
a = (test2 ==1) d=diff([0 0]) start=find(d==1) finish=find(d==-1)-1
padding 0 @ beginning , end easiest possibility. special cases group starts @ index 1 or ends @ last index don't cause problems.
full output:
>> test2 = [nan 1 1 1 0 0 0 nan nan nan 0 0 0 1 1 1 0 1 1 1 ] test2 = columns 1 through 16 nan 1 1 1 0 0 0 nan nan nan 0 0 0 1 1 1 columns 17 through 20 0 1 1 1 >> = (test2 ==1) = columns 1 through 16 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 columns 17 through 20 0 1 1 1 >> d=diff([0 0]) d = columns 1 through 16 0 1 0 0 -1 0 0 0 0 0 0 0 0 1 0 0 columns 17 through 21 -1 1 0 0 -1 >> start=find(d==1) start = 2 14 18 >> finish=find(d==-1)-1 finish = 4 16 20 >>
Comments
Post a Comment