My colleague walked into my office with a MATLAB question, a regular pasttime for us here at the MathWorks. He wanted to take every combination of one value from each of three distinct vectors. Now, this could be done easily with some nested for loops, but that really does violate the spirit in which such challenges are issued. I did not know of a function in MATLAB that did that, but I figured someone had invented that wheel before, so off to the File Exchange. A few minutes later I remembered the difference between combinations and permutations and had found two great new picks for this week.
Permutations: A great little file, with published documentation, that will find all permutations with lots of options. Combinations: Another great little utility that answered my colleague’s challenge. It was nice to see that the author, Jos, followed up on comments from reviewers and made some good enhancements to the file.
I’ve been struggling with a matlab problem of combinations and permutations for a while and came across your post here. I thought you might be able to help me out.
Let’s say I have a vector say A =[1 2 3 4] and want to find every way I can choose all the elements of A to fit in some number of bins (let’s say 3). Bin 1 could have (1, 2, 3), Bin 2 could have (4) or (0) and Bin 3 could have (4) or (0) as well. The problem isn’t quite solved by “nchoosek” because each bin could have more or less elements than the previous bin and the element choice for each bin depends on the elements not already chosen. I know that the number of possible combinations is # of elements in A^#of bins (in this case 81), because I solved it out by hand. I am looking for an easier way! I’m sorry if this sounds confusing!
If you can point me in the right direction or offer me any help I would greatly appreciate it!
Doug,
I’ve been struggling with a matlab problem of combinations and permutations for a while and came across your post here. I thought you might be able to help me out.
Let’s say I have a vector say A =[1 2 3 4] and want to find every way I can choose all the elements of A to fit in some number of bins (let’s say 3). Bin 1 could have (1, 2, 3), Bin 2 could have (4) or (0) and Bin 3 could have (4) or (0) as well. The problem isn’t quite solved by “nchoosek” because each bin could have more or less elements than the previous bin and the element choice for each bin depends on the elements not already chosen. I know that the number of possible combinations is # of elements in A^#of bins (in this case 81), because I solved it out by hand. I am looking for an easier way! I’m sorry if this sounds confusing!
If you can point me in the right direction or offer me any help I would greatly appreciate it!
Thank you,
Amanda Palazzo
I think you need to look at the problem as such. Each element of the vector can reside in exactly one of three bins.
3 * 3 * 3 * 3 or numBins ^ numElements
-Doug
Thank you very much, I was just looking for an algorithm like this!