Julia: Assignment in Arrays

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

When indexing more than one level for an array, it works fine. But when I used it to assign values, it did not. Does anyone know why A does not change below?

In  [4]: A = rand(6)  Out [4]: 6-element Array{Float64,1}:  0.111552  0.155126  0.78485   0.147477  0.362078  0.959022  In  [5]: A[3:5][[true,false,true]]  Out [5]: 2-element Array{Float64,1}:  0.78485   0.362078  In  [6]: A[3:5][[true,false,true]] = [99, 999]  Out [6]: 2-element Array{Int64,1}:   99  999  In  [7]: A  Out [7]: 6-element Array{Float64,1}:  0.111552  0.155126  0.78485   0.147477  0.362078  0.959022

回答1:

This is because indexing arrays by ranges and vectors returns a new array with the output (instead of a view into the original array). Your statement is equivalent to the following:

julia> A = rand(6) 6-element Array{Float64,1}:  0.806919  0.445286  0.882625  0.556251  0.719156  0.276755  julia> B = A[3:5] 3-element Array{Float64,1}:  0.882625  0.556251  0.719156  julia> B[[true,false,true]] = [99, 999] 2-element Array{Int64,1}:   99  999  julia> A' 1x6 Array{Float64,2}:  0.806919  0.445286  0.882625  0.556251  0.719156  0.276755  julia> B' 1x3 Array{Float64,2}:  99.0  0.556251  999.0

You can actually see that this is what Julia is doing through some of its expression utilities. Note the explicit parentheses ― it's calling setindex! on the result of indexing, which has made a copy. (GenSym() is an internal way of specifying a temporary variable):

julia> :(A[3:5][[true,false,true]] = [99, 999]) :((A[3:5])[[true,false,true]] = [99,999])  julia> expand(:(A[3:5][[true,false,true]] = [99, 999])) :(begin         GenSym(0) = (top(vect))(99,999)         setindex!(getindex(A,colon(3,5)),GenSym(0),(top(vect))(true,false,true))         return GenSym(0)     end)

The goal is to eventually have all array indexing return views instead of copies, but that's still a work-in-progress.



转载请标明出处:Julia: Assignment in Arrays
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!