Thread Subject: Generate All Possible Combination of ...

Subject: Generate All Possible Combination of ...

From: Vinh Le

Date: 19 Mar, 2010 22:06:04

Message: 1 of 5

I would like to write a small script to generate a series of array to have all possible combination of binary number.

Here is an example
n = 2, the result will be
[0,0]
[0,1]
[1,0]
[1,1]

n = 3
[0,0,0], the result will be
[0.0.1]
....
Any help would be appreciated

Subject: Generate All Possible Combination of ...

From: Matt J

Date: 19 Mar, 2010 22:19:04

Message: 2 of 5

>> n=2; dec2bin(0:2^n-1,n)-'0'

ans =

     0 0
     0 1
     1 0
     1 1

Subject: Generate All Possible Combination of ...

From: Nathan

Date: 19 Mar, 2010 22:28:26

Message: 3 of 5

On Mar 19, 3:06 pm, "Vinh Le" <lekhanhv...@gmail.com> wrote:
> I would like to write a small script to generate a series of array to have all possible combination of binary number.
>
> Here is an example
> n = 2, the result will be
> [0,0]
> [0,1]
> [1,0]
> [1,1]
>
> n = 3
> [0,0,0], the result will be
> [0.0.1]
> ....
> Any help would be appreciated

A short for loop can do this.

%%%%%%%%%%%%%%%%%%%%%%%%%
function r = permutebin(n)
rows = 2^n;
cols = log2(rows);
r = zeros(rows,cols);
for i=1:rows
r(i,:) = dec2bin(i-1,cols);
end
r = char(r);
%%%%%%%%%%%%%%%%%%%%%%%%%

call as:
r = permutebin(n)

ex:

r = permutebin(4)

%%%%%%%%%%%%%%%5
r =
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

-Nathan

Subject: Generate All Possible Combination of ...

From: Matt J

Date: 19 Mar, 2010 22:29:08

Message: 4 of 5


A few more possibilities:


(1)

A=true(2^n,n);
v=(0:2^n-1).';

for ii=n:-1:1

A(:,ii)=bitget(v,ii);
end



(2)

 ndargs=repmat({[0,1]},1,n);
 [c{1:n}]=ndgrid(ndargs{:});
 c=cellfun(@(x) x(:), c,'uni',0);
 A=[c{end:-1:1}];

Subject: Generate All Possible Combination of ...

From: Jan Simon

Date: 19 Mar, 2010 23:30:23

Message: 5 of 5

Dear Vinh!

> I would like to write a small script to generate a series of array to have all possible combination of binary number.
>
> n = 2, the result will be
> [0,0]
> [0,1] ...
>
> n = 3
> [0,0,0], the result will be
> [0.0.1]

For larger n, e.g. 100, the computation takes some time and the C-Mex VChooseKRO might be helpful:
  http://www.mathworks.com/matlabcentral/fileexchange/26242
  R = VChooseKRO(int8(0:1), n)

Good luck, Jan

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

Contact us at files@mathworks.com