MichaelGofron
MichaelGofron

Reputation: 1410

How to generate a random integer that is either 0 or 1 in MATLAB

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

Answers (3)

Mohit Rajput
Mohit Rajput

Reputation: 1

To generate either 0 or 1 randomly...

x=round(rand)

Upvotes: 0

Luis Mendo
Luis Mendo

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

Robert Seifert
Robert Seifert

Reputation: 25232

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

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

Upvotes: 4

Related Questions