所以我有一个维度为 [5,1] 的值的向量 V。对于这个向量 V[i] 中的每个值,我想生成 5 个具有平均值 V[i] 和固定 st 偏差的正态分布数字。所以最后我将得到一个矩阵 [5,5],它在 i 行上有 5 个值,其平均值为 V[i],呈正态分布。我如何在不使用 for 循环的情况下使用 Octave/Matlab 来做到这一点?实际上,我想将均值 V 的向量传递给normrnd 函数,并为向量 V 中的每个均值获取一组 n 个正态分布数。
最佳答案
将 normrnd
与数组输入结合使用
您可以将均值向量转换为矩阵并将其传递给 normrnd
。这是有效的,因为如 normrnd
's documentation 中所述,
r = normrnd(mu,sigma)
[...]To generate random numbers from multiple distributions, specify
mu
andsigma
using arrays. If bothmu
andsigma
are arrays, then the array sizes must be the same. If eithermu
orsigma
is a scalar, thennormrnd
expands the scalar argument into a constant array of the same size as the other argument. Each element inr
is the random number generated from the distribution specified by the corresponding elements inmu
andsigma
.
示例:
mu = [30; 15; 7; -60; 0]; % vector of means
std = 2; % common standard deviation
N = 4; % number of samples for each mean
result = normrnd(repmat(mu(:), 1, N), std);
使用 randn
进行隐式扩展
您可以使用标准高斯分布的样本生成一个矩阵,乘以所需的标准差,然后将所需的平均值添加到每行:
result = mu(:) + std*randn(numel(mu), N);
这之所以有效,是因为
- 改变零均值高斯分布的标准差相当于缩放;
- 改变高斯分布的均值相当于平移。
移位是使用 implicit expansion 完成的。这种方法避免了之前方法中构建重复均值的中间矩阵,并调用 randn
而不是 normrnd
,因此可能更高效。
关于matlab - 如何在octave/matlab中从均值和st.dev向量生成多重随机分布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66389532/