splitting dataset to groups with equal means
3 views (last 30 days)
Show older comments
I have a data vector which I would like to divide into n equal size groups. Now the trick is, I would like these groups to have an identical mean, or at least as similar as possible. e.g. for n=2, X=1:8 could be divided into this result X_sol=[1,2;4,3;6,5;7,8] or X_sol=[1,2;4,3;5,6;8,7], etc. where each column of X_sol has a mean of 4.5
Thanks!
0 Comments
Answers (1)
Robert
on 23 Aug 2016
If your variables are sized similarly to your example, you can take the brute force approach and use perms to test every possible arrangement.
n = 3;
x = randn(9,1)+1;
% make a list of every arrangement of x into n groups
y = reshape(perms(x),[],length(x)/n,n);
% find the combo with the least sum squared of the difference between the means
z = mean(y,2);
% take the difference with the first mean
z = bsxfun(@minus,z(:,:,2:end),z(:,1,1));
% find the one with the least sum of the squares
[z,ii]=min(sum(z.^2,3))
x=squeeze(y(ii,:,:))
mean(x)
2 Comments
Robert
on 24 Aug 2016
Your problem is a version of the Partition Problem. There are lots of clever but complex ways to approach this problem. The specifics of your data and your needs will determine which solution is best for you.
You might try the simplest first in case it is enough. Simply sort the data, then move them into groups in order.
n = 3;
data = randi(100,[90,1]);
grouped = reshape(sort(data),n,[])
mean(grouped,2)
See Also
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!