How to generate a random integer equal to 0 or 1 in MATLAB

I was looking for MATLAB documentation on how to create a random integer that is either 0 or 1.

I came across two functions randint and randi. randint seems to be deprecated in my MATLAB version, although it is in the online documentation, and randi seems to only create randoms numbers between 1 and the specified imax value.

I even created my own randint function to solve the problem, although it does not work very efficiently in my program, because it is used for large data sets:

function [ints] = randint(m,n) ints = round(rand(m,n)); end 

Is there a built-in function to create a random integer that is either 0 or 1, or is there a more efficient way to create such a function in MATLAB?

+5
source share
3 answers

It looks a little faster:

 result = rand(m,n)<.5; 

Or if you need a result like double :

 result = double(rand(m,n)<.5); 

Examples with m = 100 , n = 1e5 (Matlab 2010b):

 >> tic, round(rand(m,n)); toc Elapsed time is 0.494488 seconds. >> tic, randi([0 1], m,n); toc Elapsed time is 0.565805 seconds. >> tic, rand(m,n)<.5; toc Elapsed time is 0.365703 seconds. >> tic, double(rand(m,n)<.5); toc Elapsed time is 0.445467 seconds. 
+6
source

randi is the way to go, just define borders 1 and 0

 A = randi([0 1], m, n); 
+4
source

To generate 0 or 1 randomly ...

x = round (RAND)

0
source

Source: https://habr.com/ru/post/973111/


All Articles