Julia: Assignment in Arrays

给你一囗甜甜゛ 提交于 2019-12-05 07:45:43

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.

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