I need help finding a way to do this, although it seems as it should be pretty simple. Lets say I have a nx1
array. For example, let X=[1 1 1 .5 .4 .2 -.2 -.3 1 1 0 1]
. What I am trying to do is find where the greatest series of consecutive 1
's begins and how many 1
's are in it. For instance, using X
, the greatest series of consecutive series starts at the index 1 and is of length 3. Also, I will be using very large sets of data so I would like to try and find the most efficient and fastest way this can be done.
Asked
Active
Viewed 266 times
1

Mohsen Nosratinia
- 9,844
- 1
- 27
- 52

Math244
- 173
- 1
- 2
- 10
-
possible duplicate of [matlab - find index for when values exceeds a threshold n number of times](http://stackoverflow.com/questions/15519695/matlab-find-index-for-when-values-exceeds-a-threshold-n-number-of-times) – Dan Jul 15 '13 at 07:58
2 Answers
2
Here's one way that you could accomplish that fairly efficiently:
x = [1 1 1 0.5 0.4 0.2 -0.2 -0.3 1 1 0 1];
x1 = (x==1);
d = diff(x1(:).');
start = find([x1(1) d]==1)
len = find([d -x1(end)]==-1)-start+1
which returns
start =
1 9 12
len =
3 2 1

horchler
- 18,384
- 4
- 37
- 73
-
I tweaked the code to make work for both row- and column-vector inputs. – horchler Jul 14 '13 at 20:49
-
No I am just passing through a column vector. However, the loop is returning empty matrices, even though there are consecutive 1's in the column. – Math244 Jul 14 '13 at 21:02
-
What vector for example? And are you sure that those values are actually `==1` and not off by some epsilon? If they are just very very close to `1` then you you should be able to adapt the equation for `x1` in my code above to include a small tolerance. – horchler Jul 14 '13 at 21:04
-
Thank you! That worked by adjusting it to x>=.9. Thank you so much for your help. – Math244 Jul 14 '13 at 21:32
-
0
A function like this can help
function [start, len] = findLongestRunning(x)
y = find(diff([0;x(:)==1;0]));
[len,J] = max(y(2:2:end)-y(1:2:end));
start = y(2*J(1)-1);
end
Running on your example
>> [start, len] = findLongestRunning(x)
start =
1
len =
3
Note that the code returns the first occurence if there are more than one sequence meeting the requirements:
>> [start, len] = findLongestRunning([x 0 x])
start =
1
len =
3

Mohsen Nosratinia
- 9,844
- 1
- 27
- 52