julia - 使用 FOR 循环和函数填充数组
问题描述
我期待下面的代码会用随机的 1 和 0 填充 E,但这不会发生。我不知道为什么。
Pkg.add("StatsBase")
using StatsBase
function randomSample(items,weights)
sample(items, Weights(weights))
end
n = 10
periods = 100
p = [ones(n,periods)*0.5]
E = fill(NaN, (n,periods))
for i in 1:periods
for ii in 1:n
E(ii,i) = randomSample([1 0],[(p(ii,i)), 1 - p(ii,i)])
end
end
E
解决方案
该声明:
E(ii,i) = randomSample([1 0],[(p(ii,i)), 1 - p(ii,i)])
定义了一个局部函数E
,而不是对矩阵的赋值操作E
。利用
E[ii,i] = randomSample([1, 0],[p[ii,i], 1 - p[ii,i]])
(我已经修复了您代码中的其他错误,因此请检查差异)
为了让它运行,你还应该写:
p = ones(n,periods)*0.5