Yuseferi
Yuseferi

Reputation: 8670

Create matrix with random binary element in matlab

I want to create a matrix in matlab with 500 cell (50 row,10 column ), How I can create and initialize it by random binary digits? I want some thing like this in 50*10 scale as sample 3*4

0 1 1 1
0 0 0 0
1 1 1 1

and after it, how can get decimal equation of any row ? like row 1 is equal 7 in decimal

Upvotes: 11

Views: 19692

Answers (5)

jan-glx
jan-glx

Reputation: 9486

Through the other answares are shorter I find it rather unappealing generating random numbers with 32 or 64 bit numbers and then throwing away 31 or 63 of them... and rather go with something like:

A_dec=randi([0,2^10-1],50,1,'uint16');

And to get the bits:

A_bin=bsxfun(@(a,i)logical(bitget(a,i)),A_dec,10:-1:1);

This is also several times faster for larger arrays (R2014a, i7 930)[but that doesn't seem to be of importance for the OP]:

tic; for i=1:1000;n = randi([0,2^10-1],50000,1,'uint16'); end;toc

Elapsed time is 1.341566 seconds.

tic; for i=1:1000;n =bsxfun(@(n,i)logical(bitget(n,i)),randi([0,2^10-1],50000,1,'uint16'),10:-1:1); end;toc

Elapsed time is 2.547187 seconds. 

tic; for i=1:1000;n = rand(50000,10)>0.5; end;toc

Elapsed time is 8.030767 seconds.

tic; for i=1:1000;n = sum(bsxfun(@times,rand(50000,10)>0.5,2.^(0:9)),2); end;toc

Elapsed time is 13.062462 seconds.

binornd is even slower:

tic; for i=1:1000;n = logical(binornd(ones(50000,10),0.5)); end;toc

Elapsed time is 47.657960 seconds.

Note that this is still not optimal due to the way MATLAB saves logicals. (bits saved as bytes...)

Upvotes: 2

Sohrab
Sohrab

Reputation: 1

Or you could try it like this:

A = binornd(ones(50,10),p);

This way you also have the option to control the probability of occurrence of ones.

Upvotes: 0

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Try this:

A = rand(50, 10) > 0.5;

The decimal equivalent of the nth row is given by:

 bin2dec(num2str(A(n,:)))

or, if you prefer,

sum( A(n,:) .* 2.^(size(A,2)-1:-1:0) )   % for big endian
sum( A(n,:) .* 2.^(0:size(A,2)-1) )      % for little endian

which is several times faster than bin2dec.

Upvotes: 5

angainor
angainor

Reputation: 11810

Why not use randi to generate random integers?

A = randi([0 1], 50, 10);

and to convert a binary row to a number - as in the previous answers:

bin2dec(num2str(A(n,:)))

Upvotes: 12

bla
bla

Reputation: 26069

Another option:

 A=round(rand(50,10));

The decimal eq of the n-th row is given by:

 bin2dec(num2str(A(n,:)))

Upvotes: 5

Related Questions