简体   繁体   English

在数组中找到所有连续组的位置(MATLAB)

[英]Finding the position of all sets of consecutive ones in an Array (MATLAB)

I have an array of the following values: 我有一个以下值的数组:

  X=[1 1 1 2 3 4 1 1 1 1 5 4 2 1 1 2 3 4 1 1 1 1 1 2 2 1]

I want to get the position (the index) of all the consecutive ones in the array, and construct an array that holds the start and end positions of each set of the consecutive zeros: 我想得到数组中所有连续的位置(索引),并构造一个数组,用于保存每组连续零的起始位置和结束位置:

  idx= [1 3; 7 10; 14 15; 19 23; 26 26];

I tried to use the following functions, but I am not sure how to implement it: 我尝试使用以下函数,但我不确定如何实现它:

   positionofoness= find(X==1);
   find(diff(X==1));

How can I construct idx array ?? 我怎样才能构造idx数组?

You were almost there with your find and diff solution. 你几乎在那里find了你的finddiff解决方案。 To find all the positions where X changes from 1 , pad X with a NaN in the beginning and the end: 要找到X1变化的所有位置,请在开头和结尾填充带有NaN X

tmp = find(diff([NaN X NaN] == 1)) % NaN to identify 1st and last elements as start and end
tmp =

1      4       7    11   14   16   19   24   26  27
%start|end   start|end

Notice that every even element tmp indicates the index + 1 of where consecutive 1s end. 请注意,每个偶数元素tmp表示连续1结束的索引+ 1。

idx = [reshape(tmp,2,[])]'; % reshape in desired form
idx = [idx(:,1) idx(:,2)-1]; % subtract 1 from second column

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM