Reputation: 72
A = [011100111100]
Hi, I want to find the index of start and end 1 and make that into a sub array. I am parsing a file so I have to do this programmatically. I am programming in Matlab.
A = [011100111100]
^ ^ B = [1 1 1]
2 4 B_index = [2 4]
A = [011100111100]
^ ^ C = [1 1 1 1]
7 10C_index = [7 10]
My try
for i=1:length(A)
% Added to stop the loop froming looping more than i.
if i == A(end)
break; % stops loop
end;
if A(i) == 1 && A(i+1) == 0
start_index = i;
end;
end;
This works to find the start index but I want to find the end as well.
Upvotes: 1
Views: 75
Reputation: 112659
A = [ 0 1 1 1 0 0 1 1 1 1 0 0 ]; %// example data
ind = diff([0 A 0]); %// detect changes
start_index = find(ind==1); %// a start is a positive change
end_index = find(ind==-1)-1; %// an end is (just before) a negative change
Upvotes: 1