File Exchange

image thumbnail

Generate uniform pseudo-random integers from linear range.

version 1.4.0.0 (1.47 KB) by DS
RAND_INT(R,N) returns an n-by-n matrix containing pseudo-random integer values from range R.

1 Download

Updated 27 Jan 2014

View Version History

View License

Function that uses RAND to generate random integers in the specified linear range, as follows:

result = floor(a + (b-a+1).* rand(N)),
where specified range is [a b]

-----
Please note: There are lots of ways to do this and lots of interesting submissions on FEX which provide similar results (see below).

random numbers:

#18443 - Random Integer Generator
#5346 - MYRANDINT -- Random Integer Generation
#27942 - WWW.RANDOM.ORG random integers/sequences/strings
#27809 - Unique Random Integer List
#13007 - Random Number Generator
#21353 - True Random Integer Generator (random.org)

random arrangement:

#30189 - RANDPERMFULL (derangement)
#17981 - RANDBLOCK
#27076 - Shuffle

Cite As

DS (2021). Generate uniform pseudo-random integers from linear range. (https://www.mathworks.com/matlabcentral/fileexchange/35324-generate-uniform-pseudo-random-integers-from-linear-range), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (3)

Travis B

Sorry:
"range must be integers" --> "range bounds must be integers"
"range is integers" --> "range bounds are integers"

Travis B

Suggestions:

if (numel(R)~=2),
error('Specified range must be a matrix with 2 elements.');
end

if (~prod(1*(R==floor(R)))),
error('Specified range must be integers.');
end

Updated first error msg to match modified numel check. Second error check confirms the range is integers (It's not immediately obvious, but non-integer range bounds can result in integers outside the bounds, which may not be what the user expects.) (I don't like the 1* in prod, but prod can't handle logical (in my older version anyway) and that converts logical to double which prod can handle.)

Jan

A very well documented and nicely written function. Useful and usable, vectorized and check of inputs.
A suggestion: The check of the size of R crashs, if R has more than 2 dimensions: "if (size(R)==[1 1])". "if numel(R)==1" is saver and faster. Afterwards rejecting "numel(R)~=2" is sufficient and accepts a [2x1] column vector also.

MATLAB Release Compatibility
Created with R2007b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!