Find indexes of equal consecutive numbers in vector

11 views (last 30 days)
I have a row vector, for example: [0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1]
And I want to find the indexes of the values equal to 1.
So, in this case the outputs would be [7 8 9 10 11] and [19 20 21] because I would want this to be in separate outputs (instead of [7 8 9 10 11 19 20 21]). How can I do this automatically? Btw, my row vector has 1650 elements and several blocks of repetitions of 1's, but it should look very similar to this.
Edit: I have manage to do this using the following code, where "mask" is the name of my vector. However, I get a matrix with all the indexes, instead of separate matrices/outputs. Anyone can help me with that?
u = unique(mask(~isnan(mask)));
n = histc(mask,u);
d = u(n > 1);
out = find(ismember(mask,1));

Accepted Answer

Ameer Hamza
Ameer Hamza on 9 Sep 2020
If you have image processing toolbox
x = [0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1];
comps = bwconncomp(x);
list = comps.PixelIdxList;
Result
>> list{1}
ans =
7
8
9
10
11
>> list{2}
ans =
19
20
21

More Answers (1)

Ameer Hamza
Ameer Hamza on 9 Sep 2020
Edited: Ameer Hamza on 9 Sep 2020
Without the image processing toolbox
x = [0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0];
x_ = [diff(x) -1];
x1 = find(x_ == 1)+1;
x2 = find(x_ == -1, numel(x1));
list = arrayfun(@(x, y) {x:y}, x1, x2);
Result
>> list{1}
ans =
7 8 9 10 11
>> list{2}
ans =
19 20 21

Community Treasure Hunt

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

Start Hunting!