Julia: 如何随机创建一个大小为 n 的向量,其中只包含特定的数字?

huangapple go评论50阅读模式
英文:

Julia: how to randlomy create vector of size n having only specific numbers?

问题

我想创建一个大小为Dl = 500的随机数向量,只包含1、2或3。我使用了以下代码:

v = fill(0, Dl) # 创建一个大小为500且填充为0的向量
v[rand(1:length(v), Dl)] .= rand(1:3, Dl)

但是,我发现一些数字是0。我想要的是0、1、2、3而不只是1、2、3。问题是什么?

英文:

I'd like to create a vector of random number of size Dl =500 and only have number 1 ot 2 or 3. I did

v = fill(0, Dl) # create a vector of size 500 filled with zeros
v[rand(1:length(v), Dl)] .= rand(1:3, Dl)

However, I see that some numbers are 0. I have 0,1,2,3 not jsu t 1,2,3. What is the issue?

答案1

得分: 1

因为你同时随机化了目标索引和它们的值。

执行:

v .= rand(1:3, Dl)

足以用新的随机值就地替换 v 的值。

或者,你可以只写:

v = rand(1:3, Dl)

(不包括 fill 部分)来获得你想要的结果。

英文:

Because you are both randomizing target indices and their values.

Doing:

v .= rand(1:3, Dl)

is enough to replace values of v in-place with fresh random values.

Altenatively, you could just write:

v = rand(1:3, Dl)

(without the fill part) to get what you want.

答案2

得分: 1

这是您要翻译的部分:

我想这就是您试图实现的内容。

Dl = 500
v = fill(0, Dl) # 创建一个大小为500的用零填充的向量
v[1:Dl] .= rand(1:3, Dl)

您的问题可以用一个小一点的示例来解释:

Dl = 10
v = fill(0, Dl) # 创建一个大小为500的用零填充的向量
v[rand(1:length(v), Dl)] .= rand(1:3, Dl)

将这个问题分解成组件,我们可以看到您有:

Dl = 10
v = fill(0, Dl) # 创建一个大小为500的用零填充的向量
problem = rand(1:length(v), Dl)
v[problem] .= rand(1:3, Dl)

所以,problem 变成了一个大小为 Dl 的向量,其中 problem 的每个索引都是介于 1 和 Dllength(v) 之间的值。因此,一个可能的集合是 [1,2,6,5,8,5,10,2,4,4]。因此,您现在多次设置了索引2、5、4,但只设置了1、6、8、10一次,然后从不触及索引3、7、9。由于您将向量初始化为全部为零,它们将保持在索引3、7、9处的零状态。

英文:

I suppose this is what you are trying to achieve.

Dl =500
v = fill(0, Dl) # create a vector of size 500 filled with zeros
v[1:Dl] .= rand(1:3, Dl)

Your issue can be explained down below with a smaller set of ten:

Dl = 10
v = fill(0, Dl) # create a vector of size 500 filled with zeros
v[rand(1:length(v), Dl)] .= rand(1:3, Dl)

Breaking this down into components we can see you have:

Dl = 10
v = fill(0, Dl) # create a vector of size 500 filled with zeros
problem = rand(1:length(v), Dl)
v[problem] .= rand(1:3, Dl)

So problem becomes a vector of size Dl with at each index of problem is a value between 1 and Dl or length(v). So a possible set is [1,2,6,5,8,5,10,2,4,4]. So you are now setting the index' at 2,5,4 more than once, 1,6,8,10 only once and then never touch index 3,7,9.Because you initialized your vector to all zeros they will remain at zero in indices 3,7,9.

huangapple
  • 本文由 发表于 2023年5月11日 00:41:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定