Passing sub-arrays by reference

I am puzzled by how to pass sub-arrays of two or higher dimensional arrays by reference. I have defined the following function

julia> function ff(a::Vector) a[1]=777; end

which sets the first element to 777. However, when I pass a subarray to this function, this change is not reflected.

julia> a = rand(2,3); ff(a[1,:]); display(a);                                 
2×3 Array{Float64,2}:                                                               
0.42995   0.803084  0.927195                                                      
0.155134  0.335006  0.399494

How should I define a function so that changes made on sub-arrays are reflected ?

a[1, :] always creates a new copy. If you actually want to pass a SubArray which still references the original array to a function, you should use view(a, 1, :) instead.

3 Likes

In addition to what @simeonschaub said, you will need to widen the set of types that ff takes to something like: ff(a::AbstractVector), since the view function does not return a plain Vector. There should be no performance penalty for changing the type signature of ff to ::AbstractVector, and I would recommend always taking ::AbstractVector instead of ::Vector as function inputs unless you have some compelling reason not to.

3 Likes

@rdeits @simeonschaub I see, thank you ! I will use the view command henceforth.

1 Like