MATLAB: How to find the sequences with length bigger than n in a vector

lenghtvector

Dear, I have a vector and I need to find the sequences of consecutive numbers with length greater than or equal to 6. For example:
v = [1 2 3 4 5 6 7 10 12 16 17 18 19 20 21 24 25 30 31 32 33 34 35 36]
I would like to leave only the sequences greater than or equal to 6.
Then I would get:
r = [1 2 3 4 5 6 7 16 17 18 19 20 21 30 31 32 33 34 35 36]
Here is a part of my vector:
v = [342 344 345 346 348 351 352 353 354 355 356 357 358 359 427 428 429 430 431 432 433 434 435 436 437 438 443 444 445 446 447 448 449 450 581 582 591 881 945 947 948 949 1013 1014 1016 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1085 1100 1172 1173 1174 1175 1176 1177 1178 1179 1181 1186 1562 1581 1591 1592 1594 1595 1610 1611 1612 1626 1679 1810 1811 2064 2077 2087 2103]
If someone can help me, I'll be very grateful.

Best Answer

v = [1 2 3 4 5 6 7 10 12 16 17 18 19 20 21 24 25 30 31 32 33 34 35 36]
minlength = 6;
isconsecutive = diff(v ) == 1;
seqedges = find(diff([false, isconsecutive, false]));
seqstarts = seqedges(1:2:end);
seqstops = seqedges(2:2:end);
seqlengths = seqstops - seqstarts + 1;
tokeep = seqlengths >= minlength
indicestokeep = cell2mat(arrayfun(@(s, e) s:e, seqstarts(tokeep), seqstops(tokeep), 'UniformOutput', false);
filteredv = v(indicestokeep)