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 日

12 投票

output = dec2bin(2^n-1:-1:0)-'0'

9 件のコメント

Mohammed
Mohammed 2014 年 3 月 30 日
Thankyou very much..can't believe it could be solved in one line!!
salma ahmed
salma ahmed 2016 年 1 月 2 日
thanks alot :)
poornimasre jegan
poornimasre jegan 2018 年 6 月 28 日
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..?
Ben Krämer
Ben Krämer 2018 年 12 月 14 日
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.
Bruno Luong
Bruno Luong 2018 年 12 月 14 日
@Kramer, please open a new thread.
Saber Rahbarfam
Saber Rahbarfam 2019 年 1 月 30 日
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
S
S 2019 年 3 月 20 日
Thank you, 'the cyclist'. That was very clever.
Sodamn Insane
Sodamn Insane 2019 年 3 月 27 日
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.
Muhammad Atif Ali
Muhammad Atif Ali 2021 年 10 月 29 日
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 日

0 投票

n=3;
s=0:1;
idx=rem(nchoosek(0:2^n-1,n),2)+1;
out=flipud(unique(s(idx),'rows'))

1 件のコメント

Mohammed
Mohammed 2014 年 3 月 30 日
Thank you so much.that was quick n short

サインインしてコメントする。

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 についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by