Truncating vector to longest continuous string of numbers
Show older comments
I have a number of 10000x1 arrays with some bad data and only want to keep the longest continuous part of the array. I have spent quite a while searching but cannot find an answer.
So what I am looking for is a way for MATLAB to search each vector, find the longest continuous set of numbers above a certain value and discard the rest. This should be simple but I cannot found and easy solution.
eg m = [1,2,3,4,5,6,-5,-5,-5,1,2,3,4,5,6,7,-5,-5,-5,-5,1,2,3,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]; would return m=[ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ]
Thanks
EDIT the array is not necessarily continuous numbers.
1 Comment
dpb
on 15 Jun 2017
<Previous?> has several answers plus there's a submittal on File Exchange on finding runs--I forget the exact name but a search should uncover it...
Answers (2)
Andrei Bobrov
on 15 Jun 2017
Edited: Andrei Bobrov
on 15 Jun 2017
m=[ 1 2 3 4 5 6 -5 -5 -5 1 2 3 4 5 6 7 -5 -5 -5 -5 1 2 3 4];
z = diff(m) == 1;
z = [z(1);z(:)];
z(diff(z)==1) = 1;
a = zeros(numel(z),1);
a(diff([0;z]) == 1) = 1;
a = cumsum(a,1).*z;
n = accumarray(a+1,1);
[~,ii] = max(n(2:end));
out = m(a == ii);
or
z = diff(m) == 1;
z = [z(1),z(:)'];
z(strfind(z,[0 1])) = 1;
a = regionprops(z,'Area','PixelIdxList');
out = m(a([a.Area] == max([a.Area])).PixelIdxList);
1 Comment
nickname1
on 15 Jun 2017
>> m = [1,2,3,4,5,6,-5,-5,-5,1,2,3,4,5,6,7,-5,-5,-5,-5,1,2,3,4];
>> d = diff([false,diff(m)==1,false]);
>> vb = find(d>0);
>> ve = find(d<0);
>> [~,idx] = max(ve-vb) % which sequence is the longest
idx = 2
>> m(vb(idx):ve(idx)) % get that sequence
ans =
1 2 3 4 5 6 7
2 Comments
nickname1
on 15 Jun 2017
@nickname1: so what you want is the longest sequence of positive values? Like this?:
>> m = [1,2,3,4,5,6,-5,-5,-5,1,2,3,4,5,6,7,-5,-5,-5,-5,1,2,3,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
>> d = diff([false,m>0,false]);
>> vb = find(d>0);
>> ve = find(d<0)-1;
>> [~,idx] = max(ve-vb) % which sequence is the longest
idx = 3
>> m(vb(idx):ve(idx)) % get that sequence
ans =
1 2 3 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!