How do I create a matrix with all binary combinations?

Hi
I want to create a matrix with all binary combinations. If N is the length of the binary code, there would be possible combinations. Below are , and the 16 possible binary combinations are displayed.
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0
1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
How can I create such a matrix automatically? I don't really care which order they are in, as long as every combination is present, and N is a variable.
Thanks in advance.

 채택된 답변

the cyclist
the cyclist 2020년 5월 13일
There's an incredible obfuscated hack for this:
N = 4;
dec2bin(0:2^N-1)' - '0'

댓글 수: 1

Thanks to both of you, this worked like a charm! My N is usually less than 10, so memory shouldn't be a big problem :)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Fangjun Jiang
Fangjun Jiang 2020년 5월 13일
I though it should be
ff2n(4)

댓글 수: 2

This also worked, thanks :)
ff2n, Two-level full-factorial design, is built for this.

댓글을 달려면 로그인하십시오.

James Tursa
James Tursa 2020년 5월 13일
편집: James Tursa 2020년 5월 13일
dec2bin(0:2^N-1) - '0'
Note that this is only practical for relatively small values of N. Even moderatly large N can cause this to exceed your available memory.

댓글 수: 5

Hi, any similar method is there to extend this code for ternary strings, i.e., to generate all strings containing (0,1,2) of length N
Is this a statement or a question ?
If you have the Statistics and Machine Learning Toolbox, you can use fullfact:
L = 3; % Length
N = 2; % Values in range 0-N
v = (N+1)*ones(1,L);
output = fullfact(v) - 1
output = 27×3
0 0 0 1 0 0 2 0 0 0 1 0 1 1 0 2 1 0 0 2 0 1 2 0 2 2 0 0 0 1
N = 4; % length
base = 3;
output = dec2base(0:base^N-1,base)-'0';
disp(output);
0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 1 1 0 0 1 2 0 0 2 0 0 0 2 1 0 0 2 2 0 1 0 0 0 1 0 1 0 1 0 2 0 1 1 0 0 1 1 1 0 1 1 2 0 1 2 0 0 1 2 1 0 1 2 2 0 2 0 0 0 2 0 1 0 2 0 2 0 2 1 0 0 2 1 1 0 2 1 2 0 2 2 0 0 2 2 1 0 2 2 2 1 0 0 0 1 0 0 1 1 0 0 2 1 0 1 0 1 0 1 1 1 0 1 2 1 0 2 0 1 0 2 1 1 0 2 2 1 1 0 0 1 1 0 1 1 1 0 2 1 1 1 0 1 1 1 1 1 1 1 2 1 1 2 0 1 1 2 1 1 1 2 2 1 2 0 0 1 2 0 1 1 2 0 2 1 2 1 0 1 2 1 1 1 2 1 2 1 2 2 0 1 2 2 1 1 2 2 2 2 0 0 0 2 0 0 1 2 0 0 2 2 0 1 0 2 0 1 1 2 0 1 2 2 0 2 0 2 0 2 1 2 0 2 2 2 1 0 0 2 1 0 1 2 1 0 2 2 1 1 0 2 1 1 1 2 1 1 2 2 1 2 0 2 1 2 1 2 1 2 2 2 2 0 0 2 2 0 1 2 2 0 2 2 2 1 0 2 2 1 1 2 2 1 2 2 2 2 0 2 2 2 1 2 2 2 2
Thanks a lot....

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

릴리스

R2019a

태그

질문:

2020년 5월 13일

댓글:

2022년 12월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by