MATLAB Answers

How do I create a matrix with all binary combinations?

25 views (last 30 days)
Christian P
Christian P on 13 May 2020
Commented: Fangjun Jiang on 14 May 2020
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.

  0 Comments

Sign in to comment.

Accepted Answer

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

  2 Comments

the cyclist
the cyclist on 13 May 2020
Damn. Second to James because I add the commentary. :-)
Christian P
Christian P on 13 May 2020
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 :)

Sign in to comment.

More Answers (2)

James Tursa
James Tursa on 13 May 2020
Edited: James Tursa on 13 May 2020
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.

  0 Comments

Sign in to comment.


Products


Release

R2019a

Translated by