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 scal
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.
Another option:
A=round(rand(50,10));
The decimal eq of the n-th row is given by:
bin2dec(num2str(A(n,:)))
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,:)))
Try this:
A = rand(50, 10) > 0.5;
The decimal equivalent of the n
th 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
.
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...)