繁体   English   中英

朱莉娅的静态数组?

[英]Static array in Julia?

我有多次调用的函数,需要临时数组。 每次调用函数时都不会发生数组分配,我希望临时分配一次。

如何在Julia中创建一个静态分配的数组,具有函数范围?

好吧,让我们假设你的函数被称为foo,带有参数x ,你的数组只有100个元素(每个元素都是64位值),只有一个维度。 然后,您可以围绕该功能创建范围

let
    global foo
    let A = Array{Int64}(100)
    function foo(x)
        # do your tasks
    end
end

A应该是一个let变量,因为它会覆盖任何其他全局A

您可以将临时数组包装为类中的引用:

type MyWrapper
    thetmparray
    thefunction::Function
    function MyWrapper(outertmp::Array)
        this = new(outertmp)
        this.thefunction = function()
            #use this.thetmparray or outertmp
        end
        return this
    end
end

这样就可以避免全局变量和(将来)有一个per-executor / thread / process / machine / etc temp数组。

您可以使用let块或部分应用程序(我更喜欢这种方法):

function bind_array(A::Array) 
    function f(x)
        A = A*x
    end
end

现在,您可以将私有数组绑定到f每个新“实例”:

julia> f_x = bind_array(ones(1,2))
f (generic function with 1 method)

julia> display(f_x(2))
1x2 Array{Float64,2}:
 2.0  2.0

julia> display(f_x(3))
1x2 Array{Float64,2}:
 6.0  6.0

julia> f_y = bind_array(ones(3,2))
f (generic function with 1 method)

julia> display(f_y(2))
3x2 Array{Float64,2}:
 2.0  2.0
 2.0  2.0
 2.0  2.0

julia> display(f_y(3))
3x2 Array{Float64,2}:
 6.0  6.0
 6.0  6.0
 6.0  6.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM