[英]Pass an array containing input arguments to a function in Julia
如何將包含我想要的維度的數組傳遞給 Julia 中的ones
或rand
類ones
函數?
例如,我想執行
dims = [3 4]
rand(dims)
然后收到類似的東西
3×4 Array{Float64,2}:
0.300811 0.140124 0.756915 0.268328
0.732461 0.900773 0.251334 0.0338452
0.54227 0.439385 0.0812104 0.612996
作為輸出。
執行第一個代碼塊會返回從數組dimen = [3 4]
中隨機選擇的單個數字,但是, rand(dims = dimen)
返回ERROR: function rand does not accept keyword arguments
錯誤。
有沒有辦法做我希望做的事情?
您正在尋找的是“splat”運算符...
,如文檔中所述:
另一方面,將可迭代集合中包含的值作為單獨的參數“拼湊”到函數調用中通常很方便。 要做到這一點,還可以使用
...
但在函數調用中
在你的情況下:
julia> dims = [3 4];
julia> rand(dims...)
3×4 Array{Float64,2}:
0.664496 0.190208 0.167208 0.172296
0.632465 0.374373 0.417636 0.354948
0.743741 0.740435 0.602339 0.401814
使用splat 運算符:
julia> xs = [3 4]
1×2 Array{Int64,2}:
3 4
julia> rand(xs...)
3×4 Array{Float64,2}:
0.569082 0.953 0.44541 0.12763
0.0529293 0.470243 0.770411 0.992597
0.15326 0.248442 0.805518 0.246996
splat 運算符會將數組插入到函數調用的參數列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.