How do I make a (2^m x m) dimensional matrix containing all possible combinations of 1s and 0s?

조회 수: 4 (최근 30일)
I need to make an n x m matrix with arbitrary m such that n is the number of possible ways to write a m length vector of 1s and 0s (2^m). Example: if m=2, n=4 meaning I have: [1 0], [0 1], [0,0], and [1,1] and can construct the matrix [1 0;0 1;0 0;1 1].
I can not figure out the code to scale this up to higher m in the case where I may have m=3,4,5... and n becomes too large to enter manually. I want to be able to automatically generate the same kind of matrix for any value of m.
This is the Rstudio code someone gave me but I can't translate it:
for(j in 1:m) S <- cbind(S,rep(c(1,0),each=2^(m-j),times=2^(j-1)))
Any help would be much appreciated!
Thank you!

채택된 답변

Matt J
Matt J 2014년 2월 4일
편집: Matt J 2014년 2월 4일
The lazy way
result = dec2bin(0:2^m-1,m)-'0'

추가 답변 (1개)

Matt J
Matt J 2014년 2월 4일
A non-lazy way
[c{m:-1:1}]=ndgrid([0,1]);
result=reshape( cat(m+1,c{:}),[],m)
  댓글 수: 4
Matt J
Matt J 2014년 2월 5일
but if anyone else is interested...
If anyone else is interested, this method is preferable when speed matters. Compare,
m=20;
tic;
[c{m:-1:1}]=ndgrid([0,1]);
result=reshape( cat(m+1,c{:}),[],m) ;
toc
%Elapsed time is 0.090184 seconds.
tic;
result = dec2bin(0:2^m-1,m)-'0';
toc
%Elapsed time is 1.032300 seconds.
Thomas Casey
Thomas Casey 2014년 2월 5일
Yea it worked when I copied and pasted, I must have typed something wrong the first time. That is the fastest way, another person suggested this:
m=3;
mat = nan(2^m,m);
for idx = 1:m
mat(:,idx) = repmat([zeros(2^(m-idx),1);ones(2^(m-idx),1)],2^(idx-1),1);
end;
which is slower but still much much faster than dec2bin.
On my computer, m=3, I got 0.003s (reshape), 0.3s (dec2bin), and 0.0056s (repmat).
Thanks again!

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by