How to create a matrix out of all the possible combinations of a vector

13 ビュー (過去 30 日間)
Nora Khaled
Nora Khaled 2019 年 7 月 23 日
編集済み: Andrei Bobrov 2019 年 7 月 23 日
Hi !
I want to fill a vector with specifice numbers of 1's and -1's, and the rest are zeros. And get all possible combinations in each row of a matrix.
For example, if I have a vector of length 12 and I want to have 5 elements = +1 and 4 elements = -1
Then, the results should be like:
M=[1 1 1 1 1 -1 -1 -1 -1 0 0 0; 0 0 0 1 1 1 1 1 -1 -1 -1 -1; -1 1 1 1 1 1 -1 -1 -1 0 0 0; .....]
and every other distinct combination of the three numbers.

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 7 月 23 日
編集済み: Andrei Bobrov 2019 年 7 月 23 日
Please see answer by Roger Stafford.
In your case:
a = 3:5;
v = [0,-1,1];
n = cumsum(a,'reverse');
C1 = nchoosek(1:n(1),a(1)); % Here are the two calls on 'nchoosek'
C2 = nchoosek(1:n(2),a(2));
M = ones(size(C1,1)*size(C2,1),n(1)); % First, fill M with all 1's
k1 = 0;
for k2 = 1:size(C1,1)
p1 = C1(k2,:); % Use C1 to generate indices for inserting 0's
q1 = 1:n(1);
q1(p1) = []; % These indices will point to -1 and 1 locations
for k3 = 1:size(C2,1)
p2 = C2(k3,:); % Use C2 to generate indices for inserting -1's
k1 = k1 + 1; % Advance the row index of M
M(k1,p1) = v(1); % Insert 0's
M(k1,q1(p2)) = v(2); % and -1's
end
end
  2 件のコメント
Nora Khaled
Nora Khaled 2019 年 7 月 23 日
Thank you !
Rik
Rik 2019 年 7 月 23 日
Just out of curiosity (and because I can't test myself because I'm on mobile): does this code allow longer vectors? And if so, why? What makes this approach fundamentally different from perms()?

サインインしてコメントする。

その他の回答 (1 件)

Rik
Rik 2019 年 7 月 23 日
https://www.mathworks.com/help/matlab/ref/perms.html
  2 件のコメント
Nora Khaled
Nora Khaled 2019 年 7 月 23 日
編集済み: Nora Khaled 2019 年 7 月 23 日
Thank you for your answer!
This works for small numbers like in the example total of 10.
but it does not work with my actual implmentation it does not.
I get error msg:
Maximum variable size allowed by the program is exceeded.
Rik
Rik 2019 年 7 月 23 日
All combinations will result in a huge matrix if you have a large number of elements. As the documentation warns: this is only practical for a small number of elements. This is a fundamental problem that you need to solve separately.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by