Generate random number between -1 and 1 with specified mean and variance
8 次查看(过去 30 天)
显示 更早的评论
Hi,
I need help generating a random number between -1 and 1 with a specified mean and variance.
I'm using c=a + b*randn() with 'a' as the mean and 'b' as the standard deviation but the problem is that since the randn function only generates a mean zero standard deviation 1 random variable then I might end up having c greater or less than 1.
Thanks
0 个评论
采纳的回答
Wayne King
2011-9-18
Hi, You did not state what distribution you want the random numbers to follow. From your use of randn() in your post, I'm assuming Gaussian. In that case you can scale randn() by a factor that will reduce the variance so that the numbers lies between [-1,1].
For example, since a Gaussian random variable is expected to be essentially the mean +/- 3*standard deviation (with probability close to 1), you can use
x = (1/3)*randn(100,1);
to generate a Gaussian-distributed random sample that essentially lies with +/- 1.
You can use rand():
r = -1 + 2.*rand(100,1);
to generate a uniformly-distributed random sample on [-1,1].
Wayne
0 个评论
更多回答(2 个)
Walter Roberson
2011-9-18
It wouldn't matter. randn() always has an infinite tail, so no matter how you scale and shift to get a given mean and variance, the result will never be confined to any give range.
Perhaps you should instead use a beta distribution with a small modification to make it work over [-1,1]
0 个评论
the cyclist
2011-9-18
It is somewhat unusual (although not impossible) to have an real-world application of random numbers in which you want to specify the distribution so much (i.e. mean and variance and range). Do you mind saying what the application is? Maybe there is a better way.
Walter's suggestion of using a beta distribution is a good one. I suggest you look at the Wikipedia page (<http://en.wikipedia.org/wiki/Beta_distribution>) to see how the mean and variance depend on the alpha and beta parameters. You can use the betastat() command to also help you understand that.
The range of the beta distribution is [0,1], not [-1,1], so you'll need to transform the output. (You can multiply by 2 and subtract 1 to get the range you want.) You'll need to be careful about how that transform affects the mean and variance.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!