Reputation:
I have n sets, each having n1,n2,n3...nN distinct members. How do I generate n1*n2*n3...*nN possible combinations from them
e.g
[6] [4 5] [1 2 3 4]
will give
6 4 1
6 4 2
6 4 3
6 4 4
6 5 1
6 5 2
6 5 3
6 5 4
I want to do this in matlab, but a normal algorithm would also be fine
Upvotes: 0
Views: 1478
Reputation: 504
An easy solution is to simulate a sum !
Start with a list of indices 0 0 0, corresponding to the indices of your values. That leads you to the value 6 4 1 in your example. then add 1. You now have indices 001, so 642 and so on.
at 004, you overflow, so your indices become 010, having 6 5 1
Keep doing that, and keep a counter of the visited possibilites. There are 1 * 2 * 4 possibilities, so it's easy to know when you are done.
Upvotes: 2
Reputation: 9260
I think you're looking for Cartesian product of sets:
This should help:
cartprod(N1,N2,N3, ...)
http://www.mathworks.com/matlabcentral/fileexchange/5475-cartprod-cartesian-product-of-multiple-sets
There's another one here
set = {n1, n2, n3, ...}
allcomb(set{:})
Upvotes: 1