在数组中查找索引

时间:2014-03-28 16:36:03

标签: arrays matlab sorting for-loop

A = [011100111100]

嗨,我想找到开始和结束1的索引并将其转换为子数组。我正在解析一个文件,所以我必须以编程方式执行此操作。我在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]

我的尝试

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;

这可以找到起始索引,但我也希望找到结束。

1 个答案:

答案 0 :(得分: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