MATLAB: Putting similar numbers into groups within an array

arraycategories;matrixmatrix manipulationsorting

I have an array of numbers that looks something like follows. I want to group the array into subgroups where the numbers are all within 2 of each other. In this case, there would be 3 groups. Is there an easy way to do this? I need the method to be automated for work for arrays 100 entries long.
7340.1
7340.3
7340.6
7349.0
7349.4
7358.0
7358.1
7358.2
7358.7
% New groups would look like follows:
% Group 1
7340.1
7340.3
7340.6
% Group 2
7349.0
7349.4
% Group 3
7358.0
7358.1
7358.2
7358.7

Best Answer

If you have the Statistics and Machine Learning Toolbox (for pdist2) and the Image Processing Toolbox (for bwlabel), you can do this:
m = [...
7340.1
7340.3
7340.6
7349.0
7349.4
7358.0
7358.1
7358.2
7358.7]
% % New groups would look like follows:
% % Group 1
% 7340.1
% 7340.3
% 7340.6
% % Group 2
% 7349.0
% 7349.4
% % Group 3
% 7358.0
% 7358.1
% 7358.2
% 7358.7]
% First sort m so that close by ones has adjacent indexes.
m = sort(m, 'ascend')
% Get distance of every element to every other element.
distances = pdist2(m, m)
% Find out which pairs are within 2 of each other.
within2 = distances > 0 & distances < 2
% Erase upper triangle to get rid of redundancy
numElements = numel(m);
t = logical(triu(ones(numElements, numElements), 0))
within2(t) = 0
% Label each group with an ID number.
[labeledGroups, numGroups] = bwlabel(within2)
% Put each group into a cell array
for k = 1 : numGroups
[rows, columns] = find(labeledGroups == k);
indexes = unique([rows, columns]);
groups{k} = m(indexes);
end
celldisp(groups); % Display the results in the command window.
It gives you your desired result. Should work for other arrays also, though I didn't test it with any others.