random generator in matlab

MATLAB provides several functions to generate random numbers. The rand function generates uniformly distributed numbers between 0 and 1. The randn function generates normally distributed random numbers.

Here's an example of using rand to generate a random matrix of size 3x3:

main.m
rng('default')   % set the random number generator to its default initial state
M = rand(3)      % generate a 3x3 matrix of random numbers
139 chars
3 lines

Output:

main.m
M =

    0.8147    0.0975    0.1576
    0.9058    0.2785    0.9706
    0.1270    0.5469    0.9572
98 chars
6 lines

You can also specify the range of the random numbers using the rand function. For example, to generate a random number in the range [a,b], use:

main.m
r = (b-a)*rand + a
19 chars
2 lines

where a and b are the lower and upper bounds, respectively.

main.m
rng('default')
a = 1;
b = 10;
r = (b-a)*rand + a
49 chars
5 lines

Output:

main.m
r =

    6.9729
16 chars
4 lines

Similarly, you can use the randn function to generate normally distributed random numbers with mean 0 and standard deviation 1. The randn function takes the same input arguments as rand.

gistlibby LogSnag