使用FOR循环和函数填充数组

时间:2019-05-06 21:46:11

标签: julia

我期望以下代码将E填充为随机的1和0,但这不会发生。我不知道为什么。

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

1 个答案:

答案 0 :(得分:2)

声明:

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
相关问题