MATLAB Answers

0

Generate all possible combinations for the column vectors of a matrix

MOHAMMED ABDELGHANI BOUCHAALA さんによって質問されました 2019 年 11 月 18 日 15:35
最新アクティビティ MOHAMMED ABDELGHANI BOUCHAALA さんによって コメントされました 2019 年 11 月 18 日 21:59
If B=[1; 2] and A=[B B B...(n times B)], how to obtain the matrix C corresponding to all the possible combinations between the column vectors of A .i.e. i want to get the combinations between n copies of the same vector :
For example, for n=3 :
A =
1 1 1
2 2 2
So, 'C' can be obtained using "allcomb" function: "C=allcomb(A(:,1),A(:,2),A(:,3))"
C =
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2
In my case n is variable. How to obtain C for any value of n ?

  0 件のコメント

サインイン to comment.

1 件の回答

James Tursa
James Tursa 님의 답변 18 Nov 2019 17:55
James Tursa 님이 편집함. 18 Nov 2019 17:58
 채택된 답변

E.g.,
>> B = [1;2];
>> n = 3;
>> Bcell = arrayfun(@(k)B,1:n,'uni',false);
>> C = allcomb(Bcell{:})
Warning: NARGCHK will be removed in a future release. Use NARGINCHK or NARGOUTCHK
instead.
> In allcomb (line 63)
C =
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2
>> n = 4;
>> Bcell = arrayfun(@(k)B,1:n,'uni',false);
>> C = allcomb(Bcell{:})
Warning: NARGCHK will be removed in a future release. Use NARGINCHK or NARGOUTCHK
instead.
> In allcomb (line 63)
C =
1 1 1 1
1 1 1 2
1 1 2 1
1 1 2 2
1 2 1 1
1 2 1 2
1 2 2 1
1 2 2 2
2 1 1 1
2 1 1 2
2 1 2 1
2 1 2 2
2 2 1 1
2 2 1 2
2 2 2 1
2 2 2 2
Another way to make Bcell is
Bcell = {B}; Bcell(2:n) = Bcell(1);

  1 件のコメント

Thank you for your answer, this does exactly what i need.
Is there anything you recommend to accelerate the code knowing that:
  • I have a long 'B' vector (length(B)=100)), constitued of consecutive decimal numbers.
  • I need only the rows of 'C' that sums to a given number 'S'.

サインイン to comment.



Translated by