Truncating vector to longest continuous string of numbers
Afficher commentaires plus anciens
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 commentaire
dpb
le 15 Juin 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...
Réponses (2)
Andrei Bobrov
le 15 Juin 2017
Modifié(e) : Andrei Bobrov
le 15 Juin 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 commentaire
nickname1
le 15 Juin 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 commentaires
nickname1
le 15 Juin 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
Catégories
En savoir plus sur Dates and Time dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!