Generate a matrix of combinations without repetition (array exceeds maximum array size preference)

47 ビュー (過去 30 日間)
Hey,
I am trying to generate a matrix, that has all unique combinations of [0 0 1 1], I wrote this code for this:
v1 = [0 0 1 1];
M1 = unique(perms([0 0 1 1]),'rows');
This isn't ideal, because perms() is seeing each vector element as unique and doing 4! = 4 * 3 * 2 * 1 = 24 combinations.
With unique() I tried to delete all the repetitive entries so I end up with the combination matrix M1 -> only [4!/ 2! * (4-2)!] = 6 combinations!
Now, when I try to do something very simple like:
n = 15;
i = 1;
v1 = [zeros(1,n-i) ones(1,i)];
M = unique(perms(vec_1),'rows');
Instead of getting [15!/ 1! * (15-1)!] = 15 combinations, the perms() function is trying to do 15! = 1.3077e+12 combinations and it's interrupted.
How would you go about doing in a much better way? Thanks in advance!

採用された回答

Jan
Jan 2021 年 10 月 25 日
編集済み: Jan 2021 年 10 月 25 日
Instead of permuting [0,0,1,1] and removing the duplicates, you can obtain the list of indices of the ones (or zeros):
M1 = unique(perms([0 0 1 1]), 'rows')
M1 = 6×4
0 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 0 1 0 1 1 0 0
nDigit = 4;
nOnes = 2;
index = nchoosek(1:nDigit, nOnes) % Indices of 2 ones in 4 elements
index = 6×2
1 2 1 3 1 4 2 3 2 4 3 4
n = size(index, 1);
v = (1:n).' + n * (index - 1);
M2 = zeros(n, nDigit);
M2(v(:)) = 1
M2 = 6×4
1 1 0 0 1 0 1 0 1 0 0 1 0 1 1 0 0 1 0 1 0 0 1 1
The sorting order differs from the unique(perms()) solution.
This method works well with nDigits=14 and nOnes=1

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by