Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

random

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?

like image 218
MichaelGofron Avatar asked Jul 30 '14 16:07

MichaelGofron


People also ask

How do you randomly generate a 1 or 0 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.

How do you generate a random number between 0 and 1?

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.

Does Rand in MATLAB include 0 and 1?

The Matlab function rand() excludes zero. It is using the range (0, 1).

How can be random integer values generated in MATLAB?

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.


2 Answers

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.
like image 99
Luis Mendo Avatar answered Oct 27 '22 11:10

Luis Mendo


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

A = randi([0 1], m, n);
like image 30
Robert Seifert Avatar answered Oct 27 '22 12:10

Robert Seifert