1

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.

5
  • possible duplicate of Finding islands of zeros in a sequence Commented Mar 28, 2014 at 16:38
  • Is A a double array or a scalar? Commented Mar 28, 2014 at 16:38
  • 1
    wha is this tagged C ? Commented Mar 28, 2014 at 16:43
  • @Luis Mendo Wow that is a lot like my situation, i look through it. Commented Mar 28, 2014 at 16:46
  • @Arsalan Actually it's simpler here. I think it deserves a separate answer. I've removed my duplicate vote Commented Mar 28, 2014 at 16:47

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

2 Comments

i will try it and let you know.
@Arsalan It tells you the positions where ind equals 1, that is, where a change from value 0 to 1has ocurred. That corresponds to the beginning of each run of 1 values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.