0

I'm trying to use nchoosek(v,k) to get all possible combinations of four items of value one distributed randomly over 4 positions. My goal is to get this:

[4 0 0 0;
0 4 0 0;
0 0 4 0;
0 0 0 4;
3 1 0 0;
3 0 1 0;
3 0 0 1;
1 3 0 0;
0 3 1 0;
0 3 0 1;
1 0 3 0;
0 1 3 0;
0 0 3 1;
1 0 0 3;
0 1 0 3;
0 0 1 3;
2 2 0 0;
2 0 2 0;
2 0 0 2;
0 2 2 0;
0 2 0 2;
0 0 2 2;
2 1 1 0;
2 1 0 1;
2 0 1 1;
1 2 1 0;
1 2 0 1;
0 2 1 1;
1 1 2 0;
1 0 2 1;
0 1 2 1;
1 1 0 2;
1 0 1 2;
0 1 1 2;
1 1 1 1];

However I'm not sure how to input v and k correctly to achieve this with nchoosek(). Whatever I put into v, I also get as an output.

nchoosek([1,1,1,1], 4)
[1,1,1,1]

nchoosek([1,0,0,0], 4)
[1,0,0,0]

nchoosek([4,0,0,0], 4)
[4,0,0,0]

nchoosek([1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1], 4)
Error using nchoosek (line 29)
The first argument has to be a scalar or a vector.

In short I don't get the input and output of nchoosek(v,k). Anybody know how to do this? I looked up some questions here but they didn't help me along.

Community
  • 1
  • 1
Leo
  • 1,757
  • 3
  • 20
  • 44

1 Answers1

3

brute force solution:

[d1,d2,d3,d4]=ndgrid(0:4,0:4,0:4,0:4);
d = d1+d2+d3+d4;
i = find(d==4);
[d1(i),d2(i),d3(i),d4(i)]
lanpa
  • 1,319
  • 9
  • 12
  • Thats not too much code to solve it, thanks. I was hoping to just call a function, maybe nchoosek just doesnt do what I thought it did. – Leo Dec 11 '14 at 12:06