Matrix with all possibilities

3 ビュー (過去 30 日間)
Rik
Rik 2012 年 12 月 28 日
回答済み: Antonio Adaldo 2021 年 1 月 20 日
Dear all,
I would like to create a matrix with all possibilities, such as the following: [1 1 1; 1 1 0; 1 0 1; 0 1 1; 1 0 0; 0 1 0; 0 0 1; 0 0 0]
I have tried to use nchoosek([0 0 0 1 1 1],3) but this function fails in ordering. Furthermore I tried C = npermutek([ones(1,3) zeros(1,3)],3); D = unique(C,'rows'), but this one gives a out of memory error for larger vectors (8 instead of 3). For this function see: http://www.mathworks.com/matlabcentral/fileexchange/11462-npermutek/
How to create such a matrix?

回答 (4 件)

Jan
Jan 2012 年 12 月 28 日
Searching the FileExchange for the terms "combinations" and "permutations" helps to find:

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 28 日
編集済み: Azzi Abdelmalek 2012 年 12 月 28 日
out=[]
n=3
for k=1:n
s=[ones(2^(n-k ),1) ;zeros(2^(n-k ),1)]
s=repmat(s,2^(k-1),1)
out=[out s]
end

Roger Stafford
Roger Stafford 2012 年 12 月 29 日
Here is a variation on Azzi's solution:
A = ones(2^n,n);
p = 1;
for k = 0:n-1
A(p+1:2*p,n-k:n) = [zeros(p,1),A(1:p,n-k+1:n)];
p = 2*p;
end
To count up instead of down, swap the 'ones' and 'zeros' calls.

Antonio Adaldo
Antonio Adaldo 2021 年 1 月 20 日
The matrix that you want is the same as the matrix containing the binary digits of the numbers from zero to seven. For example: "0 0 0" is zero, "0 0 1" is one, "0 1 0" is two, etc.
If you have Communications Toolbox installed, MATLAB offers the function "de2bi" to produce that matrix. For example:
de2bi(0:7)
ans =
0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1
Documentation for "de2bi" is found here: https://www.mathworks.com/help/comm/ref/de2bi.html

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by