Getting all the combinations of 4 vectors?

17 次查看(过去 30 天)
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.

采纳的回答

Konstantinos Sofos
Konstantinos Sofos 2015-3-21
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,
  1 个评论
Lliam
Lliam 2015-3-21
编辑:Lliam 2015-3-21
Thanks this is exactly what I was looking for, as it allows me to easily modify the vectors.
However, now i need to figure out how: combs, cat, and ngrid actually work lol, Thanks!

请先登录,再进行评论。

更多回答(3 个)

Roger Stafford
Roger Stafford 2015-3-21
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.)

Dean Ranmar
Dean Ranmar 2019-4-17
What about allcomb?

John D'Errico
John D'Errico 2015-3-21
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

类别

Help CenterFile Exchange 中查找有关 Number Theory 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by