How to find all blocks of numbers with consecutive locations which are less than a value in an array ?

6 views (last 30 days)
Hi, I need to find all blocks of numbers (less than a specific value) with consecutive locations in an array. For example, I have [12 13 14 15 13 12 4 5 4 6 11 10 10 3 9 10 11 2 1 5], and want to get all blocks of numbers less than 7: [4 5 4 6], [3], [2 1 5]. How can I achieve it in a efficient way? Thank you very much!

Accepted Answer

Guillaume
Guillaume on 5 Nov 2015
Well, finding the numbers less than 7 is trivial. Once you've done that, you've got a logical array of 0 and 1. So the problem becomes finding the location of the 1 in the logical array. There are a few ready made function in the File Exchange, but in any case
diff([0 logical_array 0])
will result in 1 for the start of the 1 block and -1 just after the end of the same block.
a = [12 13 14 15 13 12 4 5 4 6 11 10 10 3 9 10 11 2 1 5];
threshold = 7;
transitions = diff([0, a < threshold, 0]);
runstarts = find(transitions == 1);
runends = find(transitions == -1) - 1;
blocks = arrayfun(@(s, e) a(s:e), runstarts, runends, 'UniformOutput', false);
celldisp(blocks)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!