2014-06-20 53 views
20

我從matlab遷移到julia,我試圖在1範圍內生成一個隨機整數:N範圍內生成隨機整數朱莉婭

n < 21

rand(r[1:n])作品。

然而

n > 20,e.g rand(r[1:21])

我得到這個消息。

ERROR: BoundsError() in getindex at range.jl:121

+0

'r'是什麼?可能是20元素的矢量?如果我正確地理解了你,'rand(1:n)'應該是你需要的。 –

+0

什麼是'r'?試試'蘭特(1:21)'。 – jverzani

回答

28

你可以給一個範圍內的第一個參數rand,如rand(1:n)

julia> rand(1:10) 
7 

julia> rand(1:10,10,10) 
10x10 Array{Int64,2}: 
10 2 5 8 5 5 3 7 1 3 
    5 1 4 2 4 4 1 6 6 9 
    8 1 3 9 4 8 7 8 7 10 
    3 8 1 5 7 9 7 8 10 7 
    5 8 5 6 6 2 2 7 4 3 
10 4 8 8 10 5 1 10 5 1 
    6 1 8 1 6 5 7 10 6 10 
    5 10 2 5 4 5 4 1 3 9 
    5 4 6 4 4 1 7 8 1 5 
10 2 6 4 3 10 7 3 8 7 

的第一個參數一般rand功能通常給出一個「東西從採樣」,無論是如Distributions.jl中定義的一系列值或分佈對象。

+0

'rand(S)'在S上使用統一採樣還是其他概率分佈?我的意思是如果我想生成統一的隨機整數,我通常會做'rand(Uniform(1,n))',然後我應用'ceil(Int,...)'或'floor(Int,...) 。但是我認爲,寫'rand(1:n)'是更正確的 - 如果採樣是uniform_。 – Ribz