Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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 ??

like image 680
ryh12 Avatar asked Dec 06 '25 21:12

ryh12


1 Answers

You were almost there with your find and diff solution. To find all the positions where X changes from 1, pad X with a NaN in the beginning and the end:

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.

idx = [reshape(tmp,2,[])]'; % reshape in desired form
idx = [idx(:,1) idx(:,2)-1]; % subtract 1 from second column
like image 112
Some Guy Avatar answered Dec 08 '25 12:12

Some Guy