User`s guide
9 GPU Computing
9-16
Generate Random Numbers on a GPU
The function you pass to arrayfun or bsxfun for execution on a GPU can contain the
random number generator functions rand, randi, and randn. However, the GPU does
not support the complete functionality that MATLAB does.
arrayfun and bsxfun support the following functions for random matrix generation on
the GPU:
rand
rand()
rand('single')
rand('double')
randn
randn()
randn('single')
randn('double')
randi
randi()
randi(IMAX, ...)
randi([IMIN IMAX], ...)
randi(..., 'single')
randi(..., 'double')
randi(..., 'int32')
randi(..., 'uint32')
You do not specify the array size for random generation. Instead, the number of
generated random values is determined by the sizes of the input variables to your
function. In effect, there will be enough random number elements to satisfy the needs of
any input or output variables.
For example, suppose your function myfun.m contains the following code that includes
generating and using the random matrix R:
function Y = myfun(X)
R = rand();
Y = R.*X;
end
If you use arrayfun to run this function with an input variable that is a gpuArray, the
function runs on the GPU, where the number of random elements for R is determined
by the size of X, so you do not need to specify it. The following code passes the gpuArray
matrix G to myfun on the GPU.
G = 2*ones(4,4,'gpuArray')
H = arrayfun(@myfun, G)
Because G is a 4-by-4 gpuArray, myfun generates 16 random value scalar elements for R,
one for each calculation with an element of G.
Random number generation by arrayfun and bsxfun on the GPU uses the same global
stream as gpuArray random generation as described in “Control the Random Stream