Getting all the combinations of 4 vectors?
17 views (last 30 days)
Show older comments
Problem: I want to get the combinations of 4 vectors so that my output would look something like this:
(all 4 vectors are the same vec=[1:9])
1 1 1 1
1 1 1 2
1 1 1 3
...
1 1 1 9
1 1 2 1
1 1 2 2
1 1 2 3 etc etc
and it would just keep counting up until it reaches 9 9 9 9. Normally, I would use for loops in other languages but I thought I could use the combo feature in matlab.
My Solution: My goal was to test my idea with smaller numbers to see if I could get the combos of 2 vectors from [1:3] and only choosing 2.
Here is what I tried,
vec1=[1:2];
vec2=[1:2];
combos=combnk([vec1 vec2],2)
Output was:
1 2
2 2
2 1
1 2
1 1
1 2
The problem is, it is double counting the combo: 1 2. Am i using the function wrong? I would appreciate any help.
0 Comments
Accepted Answer
Konstantinos Sofos
on 21 Mar 2015
Hi,
The ndgrid function almost gives the answer, but has one caveat: n output variables must be explicitly defined to call it. Since n is arbitrary, the best way is to use a comma-separated list (generated from a cell array with ncells) to serve as output. The resulting n matrices are then concatenated into the desired n-column matrix:
As an example:
vectors = { [1 2], [3 6 9], [10 20] }; %input data: cell array of vectors
n = numel(vectors); % number of vectors
combs = cell(1,n); % pre-define to generate comma-separated list
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); % the reverse order in these two
% comma-separated lists is needed to produce the rows of the result matrix
combs = cat(n+1, combs{:}); %concat the n n-dim arrays along dimension n+1
combs = reshape(combs,[],n); %reshape to obtain desired matrix
Regards,
More Answers (3)
Roger Stafford
on 21 Mar 2015
This is the wrong function for your problem. Your problem has 9^4 = 6561 rows of values, which does not correspond to anything generated by 'combnk'. I would suggest Matt Fig's COMBINATOR function in the File Exchange using "permutations with replacement". (A "permutation" with replacement is something of a misuse of the term 'permutation' since it allows such vectors as 1 1 1 1, but that is what you need.)
John D'Errico
on 21 Mar 2015
A = dec2base(1111:9999,10) - '0';
A(1:20,:)
ans =
1 1 1 1
1 1 1 2
1 1 1 3
1 1 1 4
1 1 1 5
1 1 1 6
1 1 1 7
1 1 1 8
1 1 1 9
1 1 2 0
1 1 2 1
1 1 2 2
1 1 2 3
1 1 2 4
1 1 2 5
1 1 2 6
1 1 2 7
1 1 2 8
1 1 2 9
1 1 3 0
...
A(end,:)
ans =
9 9 9 9
3 Comments
See Also
Categories
Find more on Number Theory 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!