Number of ways of distributing n distinct objects into r identical groups

7 views (last 30 days)
I'm trying to figure out the logic to how I may generate every possible combination of n rows of a matrix into r number of groups, and then store each combination in a cell array.
For example, if I had a matrix:
[2 4 6; 20 40 60; 200 400 600]
Then, n =3. I then want to see every grouping possibility into r=2 groups.
The possibilities are:
1)
[2 4 6] and [20 40 60; 200 400 600]
2)
[20 40 60] and [2 4 6; 200 400 600]
3)
[200 400 600] and [2 4 6; 20 40 60]
4)
[ 2 4 6; 20 40 60; 200 400 600] and [ ]
Then have each of the possibilities stored cell arrays in a larger cell array. Something like:
possibility1 = cell(1,2);
possibility1{1,1} = [2 4 6];
possibility1{1,2} = [20 40 60; 200 400 600];
combinations = cell(4,1) % larger cell array to store the possibilities
combinations{1,1} = possibility1
etc.
But done so in a loop as you iterate through generating each possibility.

Answers (1)

Elizabeth Reese
Elizabeth Reese on 31 Aug 2017
Based on your description, it looks like there are two separate concepts that you are dealing with. The first is that you need to know how many ways you can partition the n elements in r groups. I suggest taking a look at Integer Partition Generators for this such as these File Exchange submissions.
Once you know the partitions, you can pad them with 0's or eliminate partitions that have more than r elements. This tells you how many elements go into each group.
Knowing this, you can use the MATLAB function nchoosek to tell you ways to choose which rows can go into which groups. For this, I recommend using the vector input with v = 1:n to represent the row indices and then when it is time to create your cell array, you can use A(i,:) to index into the matrix.

Categories

Find more on Loops and Conditional Statements 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!