本文介绍了生成非负随机数(Matlab)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Matlab中生成一个N维列向量,平均值为0.5(可以调整方差),但是我希望所有数字都是正数,有人知道怎么做吗?

I want to generate a N dimensional column vector in matlab, with mean 0.5 ( variance is ok to adjust ) , but I want all numbers to be positive, does anyone know how to do it?

推荐答案

这取决于您想要的分布. rand(v)函数在尺寸为v的数组中生成均匀的随机分布(我相信范围是[0,1],尽管我不确定0或1在理论上是否是可能的值).

It depends on the distribution that you want. The rand(v) function generates a uniform random distribution (range [0,1] I believe although I'm not sure if either 0 or 1 are theoretically possible values) in an array with dimensions v.

因此,如果要使用3x4x5x6数组,则可以这样做

So if you want a 3x4x5x6 array, you would do

myRandArray = rand([3 4 5 6]);

如果您希望上限值更大,可以这样做

If you want the upper value to be larger, you could do

myRandArray = maxVal * rand([3 4 5 6]);

maxVal是最大值.而且,如果您希望范围从minValmaxVal,请这样做

Where maxVal is the largest value. And if you want a range minVal to maxVal, then do

myRandArray = minVal + (maxVal - minVal) * rand([3 4 5 6]);

对于其他发行版(例如,对于正常发行版的randn),显然可以对上述内容进行调整.如果您希望正态分布被截断"-您可能需要以太多的值开头:

For other distributions (like randn for normal distribution) you can make adjustments to the above, obviously. If you want a "truncated normal distribution" - you may need to start with too many values:

dims = [3 4 5 6];
n = prod( dims );
tooMany = 0.5 + randn(2 * n); % since you want mean = 0.5
tooMany(tooMany < 0) = [];
if numel( tooMany ) > n
  myRandArray = reshape(tooMany(1:n), dims);
end

您显然可以对此进行改进,但这是一个普遍的想法.

You can obviously improve on this, but it's a general idea.

例如,您可以仅生成n个值,查看有多少个失败(例如m),然后生成另一个m * n/(n-m),然后根据需要重复,直到精确到n.

For example, you could generate only n values, see how many fail (say m), then generate another m * n / (n - m), and repeat as needed until you have exactly n.

请注意,由于我们切除了尾巴,因此最终分布的均值不再是0.5.如果排除某些值,则正态分布"不能保持正态".但是然后您没有指定您想要的分布...

Note that the mean of the final distribution is no longer 0.5 since we cut off the tail. A 'normal distribution' cannot remain 'normal' if you exclude certain values. But then you didn't specify what distribution you wanted...

这篇关于生成非负随机数(Matlab)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:45