Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Assignment in Arrays

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
like image 450
Pooya Avatar asked Apr 20 '15 19:04

Pooya


1 Answers

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.

like image 51
mbauman Avatar answered Dec 31 '22 18:12

mbauman