I searched the MATLAB documentation for how to generate a random integer that is either a 0 or a 1.
I stumbled upon the two functions randint and randi. randint appears to be deprecated in my version of MATLAB although it is in the documentation online and randi appears to only create randoms numbers between 1 and a specified imax value.
I even created my own randint function to solve the problem although it doesn't run very efficiently in my program since 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 a 0 or 1 or is there a more efficient way to create such a function in MATLAB?
The rand function returns floating-point numbers between 0 and 1 that are drawn from a uniform distribution. For example: rng('default') r1 = rand(1000,1); r1 is a 1000-by-1 column vector containing real floating-point numbers drawn from a uniform distribution.
Using the random.The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.
The Matlab function rand() excludes zero. It is using the range (0, 1).
Create a 1-by-1000 array of random integer values drawn from a discrete uniform distribution on the set of numbers -10, -9,...,9, 10. Use the syntax, randi([imin imax],m,n) . r = randi([-10 10],1,1000); Verify that the values in r are within the specified range.
This seems to be a little faster:
result = rand(m,n)<.5;
Or, if you need the result as 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.
randi
is the way to go, just define the boundaries to 1 and 0
A = randi([0 1], m, n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With