Create matrix with random binary element in matlab

前端 未结 5 866
情歌与酒
情歌与酒 2021-01-11 16:57

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

相关标签:
5条回答
  • 2021-01-11 17:17

    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.

    0 讨论(0)
  • 2021-01-11 17:37

    Another option:

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

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

     bin2dec(num2str(A(n,:)))
    
    0 讨论(0)
  • 2021-01-11 17:39

    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,:)))
    
    0 讨论(0)
  • 2021-01-11 17:41

    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.

    0 讨论(0)
  • 2021-01-11 17:43

    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...)

    0 讨论(0)
提交回复
热议问题