您的位置:首页 > 编程语言 > MATLAB

MATLAB随机函数rand

2011-06-17 14:33 881 查看
转自:http://350245658.blog.163.com/blog/static/164473440201042194910783/



rand产生的是0到1(不包括1)的随机数.

matlab的rand函数生的是伪随机数,即由种子递推出来的,相同的种子,生成相同的随机数.

matlab刚运行起来时,种子都为初始值,因此每次第一次执行rand得到的随机数都是相同的.

1.多次运行,生成相同的随机数方法:

用rand('state',S)设定种子
S为35阶向量,最简单的设为0就好

例:

rand('state',0);rand(10)

2. 任何生成不同的随机数方法:

试着产生和时间相关的随机数,种子与当前时间有关.

rand('state',sum(100*clock))

即:

rand('state',sum(100*clock)) ;rand(10)

只要执行rand('state',sum(100*clock)) ;的当前计算机时间不同,生成的随机值就不同.

也就是如果时间相同,生成的随机数还是会相同.

在你计算机速度足够快的情况下,试运行一下:

rand('state',sum(100*clock));A=rand(5,5);rand('state',sum(100*clock));B=rand(5,5);

A和B是相同.

所以建议再增加一个随机变量,变成:

rand('state',sum(100*clock)*rand(1));



MATLAB自带的rand帮助:

RAND Uniformly distributed random numbers. 标准化分布的随机数
RAND(N) is an N-by-N matrix with random entries, chosen from a uniform distribution on the interval (0.0,1.0). rand(N)为随机生成一个在【0,1】之间的n维随机矩阵。
RAND(M,N) and RAND([M,N]) are M-by-N matrices with random entries.随机生成一个在【0,1】之间的m,n维随机矩阵。
RAND(M,N,P,...) or RAND([M,N,P,...]) generate random arrays.
RAND with no arguments is a scalar whose value changes each time it is referenced. RAND(SIZE(A)) is the same size as A.

RAND produces pseudo-random numbers. The sequence of numbers generated is determined by the state of the generator. Since MATLAB resets the state at start-up, the sequence of numbers generated will be the same unless the state is changed. matlab的随机数算法是通过一个“种子”递推出来的, 种子在程序初始的时候都一样。
S = RAND('state') is a 35-element vector containing the current state of the uniform generator. RAND('state',S) resets the state to S.
RAND('state',0) resets the generator to its initial state. 重新恢复初始状态,刚运行matlab时候的状态
RAND('state',J), for integer J, resets the generator to its J-th state. 安排种子产生第j个状态
RAND('state',sum(100*clock)) resets it to a different state each time.根据时间产生不同的随机数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: