Create matrix with random binary element in matlab

前端 未结 5 925
情歌与酒
情歌与酒 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: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...)

提交回复
热议问题