Julia:数组中的赋值 [英] Julia: Assignment in Arrays
问题描述
当为数组索引多个级别时,它可以正常工作.但是当我用它来赋值时,它没有.有谁知道为什么 A
下面没有改变?
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
推荐答案
这是因为按范围和向量索引数组会返回一个带有输出的新数组(而不是原始数组的视图).您的声明相当于以下内容:
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
您实际上可以通过一些表达式实用程序看到 Julia 正在做的事情.注意显式括号——它调用了 setindex!关于索引的结果,它已经做了一个副本.(GenSym() 是一种指定临时变量的内部方式):
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:数组中的赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!