Reputation: 1410
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?
Upvotes: 6
Views: 5780
Reputation: 112749
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.
Upvotes: 7
Reputation: 25232
randi
is the way to go, just define the boundaries to 1 and 0
A = randi([0 1], m, n);
Upvotes: 4