Generate a matrix of combinations without repetition (array exceeds maximum array size preference)
27 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Jan
on 25 Oct 2021
Edited: Jan
on 25 Oct 2021
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')
nDigit = 4;
nOnes = 2;
index = nchoosek(1:nDigit, nOnes) % Indices of 2 ones in 4 elements
n = size(index, 1);
v = (1:n).' + n * (index - 1);
M2 = zeros(n, nDigit);
M2(v(:)) = 1
The sorting order differs from the unique(perms()) solution.
This method works well with nDigits=14 and nOnes=1
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!