How would one go about generating a matrix with all the possible combinations of number totaling to a sum with repetition?
Basically, combinations of x1
, x2
, x3
such that x1 + x2 + x3 = n
.
For example: n =3
0 1 2
0 2 1
1 0 2
1 2 0
1 1 1
Is there simple way of doing this using predefined Matlab functions?
I tried
n=6;
nchoosek(0:n,3)
which gives me
0 1 2
0 1 3
0 1 4
0 1 5
0 1 6
0 2 3
0 2 4
0 2 5
0 2 6
0 3 4
0 3 5
0 3 6
0 4 5
0 4 6
0 5 6
1 2 3
1 2 4
1 2 5
1 2 6
1 3 4
1 3 5
1 3 6
1 4 5
1 4 6
1 5 6
2 3 4
2 3 5
2 3 6
2 4 5
2 4 6
2 5 6
3 4 5
3 4 6
3 5 6
4 5 6
How would one extract all rows that have the total equal to n
?
I think linear indexing or find
should make it possible, but I don't know how to go about that.
Regards