All possible combination based on 2^n

8 Ansichten (letzte 30 Tage)
BeeTiaw
BeeTiaw am 14 Mai 2021
Bearbeitet: BeeTiaw am 14 Mai 2021
I want to create a matrix containing all possible combination. Example of this is shown below. The size of the matrix depends on the number of variable n and the total of combination should follow the . The example below is valid for and, hence, the total number of rows is 8. The value of each element is 0 and 1.
How to create this matrix automatically depending on the number of variable n?

Akzeptierte Antwort

Stephen23
Stephen23 am 14 Mai 2021
Bearbeitet: Stephen23 am 14 Mai 2021
n = 3;
m = dec2bin(0:pow2(n)-1)-'0' % limited precision
m = 8×3
0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
Or
C = cell(1,n);
[C{:}] = ndgrid(0:1);
C = cellfun(@(a)a(:),C,'uni',0);
M = [C{:}]
M = 8×3
0 0 0 1 0 0 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1

Weitere Antworten (3)

Dyuman Joshi
Dyuman Joshi am 14 Mai 2021
y = flipud(dec2bin(0:2^n-1,n))-'0' %method 1
y = dec2bin(2^n-1:-1:0,n)-'0' %method 2
Choose any of the methods you wish, both give the same result.
P.S - There is a similar question in Cody as well.
  2 Kommentare
Dyuman Joshi
Dyuman Joshi am 14 Mai 2021
I see that I am late to the party
BeeTiaw
BeeTiaw am 14 Mai 2021
Bearbeitet: BeeTiaw am 14 Mai 2021
I have another question. Quite similar but the output will be slightly different.
https://uk.mathworks.com/matlabcentral/answers/829783-all-possible-combination-based-on-2-n-but-with-1-and-1

Melden Sie sich an, um zu kommentieren.


Stephan
Stephan am 14 Mai 2021
n = 3
n = 3
ff2n(n)
ans = 8×3
0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
  1 Kommentar
Stephen23
Stephen23 am 14 Mai 2021
Bearbeitet: Stephen23 am 14 Mai 2021
Note: requires the Statistics and Machine Learning Toolbox.

Melden Sie sich an, um zu kommentieren.


Bjorn Gustavsson
Bjorn Gustavsson am 14 Mai 2021
You could use dec2bin:
allpossibles = dec2bin(0:(2^n-1));
You'll have to extract the indices from the columns but that should be "not hard". There's more than likely many prettier solutions, for example have a look on the file exchange for nextperm (by Jos) and next-combination-permutation (by Matt-Fig).
HTH

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by