Tag: generator

Generating Pseudo Random Numbers in MATLAB

I wrote the code found in this post in the Student Version of MATLAB R2009a (7.8.0.347) on Windows Vista SP2.

function U = js_randv(i, x)
%js_randv Pseudo Random Number Vector Generator
% Returns a pseudo random number vector
% according to congruential random number generator
%   i = length of vector
%   x = seed value of sequence
%   U = vector of Xi+1 = (a * Xi) mod m

isFirst = 0;

a = 16807;          % 7^5 predetermined multiplicative value
m = 2147483647;     % 2^31-1 predetermined prime number
r = 2836;           % m div a
q = 127773;         % m mod a
T = zeros(1, i);    % holds seed values
U = zeros(1, i);    % holds returned uniform random numbers in (0,1)

% loop through all indices of vector
for j=1:i
    % if this is the first value, use seed
    if isFirst == 0
        seed = (a * mod(x, q)) - (r * (x / q));
        T(1, j) = seed;
        isFirst = 1;
    % if this is not the first value, use current index
    else
        previousValue = T(1, j-1);
        seed = (a * mod(previousValue, q)) - (r * (previousValue / q));
        T(1, j) = seed;
    end

	U(1, j) = seed / m;
end
end

This function will return a vector of size i containing randomly generated numbers uniformly distributed between 0 and 1. It’s not perfect, but it got the job done. I’ll get around to explaining it more beyond the meager comments another time.

References:
Generating Random Numbers
Linear congruential generatorRead more