How to sort an array into groups with a minimum of 1 entry per group?
Show older comments
The code shown for the following array sorts it into 3 groups. It doesn't put the first number (7300.0) into a group because it would be by itself. Is there a way to alter this code so that it makes 4 groups and allows for one of the groups to have a single entry?
m = [...
7300.0
7340.1
7340.3
7340.6
7349.0
7349.4
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.
Accepted Answer
More Answers (0)
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!