Create a matrix of binary numbers generated by sequence

I want to create a general matrix to create outputs of the below format...
if n=1
output=[1 0]
if n=2
output=[1 1
1 0
0 1
0 0]
if n=3
output=[1 1 1
1 1 0
1 0 1
1 0 0
0 1 1
0 1 0
0 0 1
0 0 0]
for any number of n; the output matrix will be of the order of [2^n X n]

 채택된 답변

the cyclist
the cyclist 2014년 3월 30일
output = dec2bin(2^n-1:-1:0)-'0'

댓글 수: 9

Thankyou very much..can't believe it could be solved in one line!!
thanks alot :)
thank you very much. but it is not works when n is large.what should i do if n is more than 30 or 40 etc..?
Thank you very much!
I am quite new to MATLAB and trying to figure out how I can add constraints to your solution.
What I am trying to get, is a Matrix of all the solution for n=8 that contain at least 5 1s.
I hope someone can help me out here.
@Kramer, please open a new thread.
Hello,
Can you please explain what is '0' in this code: output = dec2bin(2^n-1:-1:0)-'0', and what is it doing?
Thanks
Saber
Thank you, 'the cyclist'. That was very clever.
The -'0' converts the output of dec2bin from a character array with each combination as a row element to a matrix with the type of double.
this - '0' was the whole trick. I wasted more than 2 hours trying to figure this out.

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

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 3월 30일
편집: Azzi Abdelmalek 2014년 3월 30일
n=3;
s=0:1;
idx=rem(nchoosek(0:2^n-1,n),2)+1;
out=flipud(unique(s(idx),'rows'))
görkem tatar
görkem tatar 2021년 6월 18일

0 개 추천

y =dec2bin(x)
x = 'dec variable'
y = 'convertion of the dec variable to bin'

카테고리

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

질문:

2014년 3월 30일

댓글:

2021년 10월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by