Extract group of identical values from an array

1 次查看(过去 30 天)
I have the array
a = [0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 0 0 1 1];
I want to extract the first and last index where a==1 as a group
o/p: [4 6; 12 15; 18 19];
Is there any efficient way to do this?
  1 个评论
Adam
Adam 2017-7-7
编辑:Adam 2017-7-7
firstIndices = find( diff(a) == 1) + 1;
lastIndices = find( diff(a) == -1);
will give you most of what you need, but you would need to make a special case for the last index which it will not find, and obviously it is more efficient to do the diff just once, etc. Shaping the results into the format you want shouldn't be difficult.

请先登录,再进行评论。

采纳的回答

José-Luis
José-Luis 2017-7-7
If you have the image-processing toolbox.

更多回答(1 个)

C.J. Harris
C.J. Harris 2017-7-7
a = [0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 0 0 1 1];
nStart = find(diff([0 a 0]) == 1);
nEnd = find(diff([0 a 0]) == -1) - 1;
nResult = [nStart' nEnd'];

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by