MATLAB: Divide a data set into 4 parts so that the sum of each part 1/4th of the total

innovative strategyMATLABoptimizationOptimization Toolbox

I want to divide a data set into four groups such that the sum of elements of each group is approximately same.
for eg: [10, 5, 1, 20, 5, 22, 4, 15]
For the above data set: sum of all the elements = 82
So, I want this data set to be divided into 4 groups such that, the sum of elements of each group is almost same.
One such possibility is
Set 1: 10, 5, 4,1
Set 2: 20
Set 3: 22
Set 4: 15,5
How do I set up this?

Best Answer

  • I'd just sort them and then take the CDF and look for percentages:
    c = cumsum(sort(data, 'ascend'));
    c = c / c(end); % Normalize from 0 to 1
    c25 = find(c>0.25, 1, 'first');
    c50 = find(c>0.5, 1, 'first');
    c75 = find(c>0.75, 1, 'first');
    At least that's one way that might work, though it would work best for lots of data rather than just a few elements like you have.