How to sort an array into groups with a minimum of 1 entry per group?

2 次查看(过去 30 天)
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.

采纳的回答

Kyle Reagan
Kyle Reagan 2017-6-29
The solution to this is to make two new arrays, n and p that are slightly different from m. Do n = m - 0.01 and p = m + 0.01. FinalVector = sort(vertcat(m,n,p)). Now perform all the operations with FinalVector in the machine learning code. This way instead of seeing the number 7300.0 by itself as seen in the example above, it will now see
7299.99
7300.00
7300.01
and can form a group of 3 with the median at your original value.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by