MATLAB: Grouping elements by conditions

grouping

I have an array [ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5]. I'm trying to group the elements that are within a window of length 1, so I get [ 1 1.2 1.5 1.9] [8 8.1] [12.3 12.5] How can this be done efficiently

Best Answer

You could try this file
x=[ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5];
label = graph_connected_components(abs(x.'-x)<=1)
groupcell = splitapply(@(g){g},x,label)