Search code examples
arraysjuliarow-removal

Julia, @view to prevent production of a new array


My old friend the 3d array called Pop, I want to remove columns (d2), across all of d3 when the value in the end of d1 == 1, so I have this code:

Pop[end, :, 1] .!=1

I thought adding @view in front of this would write the changes back to Pop, outwith producing an additional copy in memory. This code works fine

@view(Pop[ :, Pop[end, :, 1] .!=1, :])

but it does not alter the original 3d array called Pop. I could do

Pop = @view(Pop[ :, Pop[end, :, 1] .!=1, :])

but I believe this will create another copy in memory which I'm trying to avoid. What simple syntax have I missed? Thx. J


Solution

  • @view does not modify the size of the original array, it provides a "view" into it, (e.g., omitting some columns in your case). I don't think there is anything wrong with

    Pop = view(Pop, :, Pop[end, :, 1] .≠ 1, :)
    

    since now Pop is a view into your old, full Pop, but it behaves like an array, so you can modify its entries, e.g., you could then do things like

    julia> using Random # using a fixed seed for reproducibility
    
    julia> Random.seed!(0) ;
    
    julia> Pop = rand(1:5, (2,4,2)) # original Pop
    2×4×2 Array{Int64,3}:
    [:, :, 1] =
     4  3  5  5
     1  1  3  5
    
    [:, :, 2] =
     2  2  3  1
     2  5  1  1
    
    julia> Pop[end,:,1] .≠ 1 # columns to keep
    4-element BitArray{1}:
     0
     0
     1
     1
    
    julia> Pop = view(Pop, :, Pop[end, :, 1] .≠ 1, :) # make it a view
    2×2×2 view(::Array{Int64,3}, :, [3, 4], :) with eltype Int64:
    [:, :, 1] =
     5  5
     3  5
    
    [:, :, 2] =
     3  1
     1  1
    
    julia> Pop[end,:,1] .= 1 ; # use your new view to manipulate data
    
    julia> Pop # view of the modified Pop
    2×2×2 view(::Array{Int64,3}, :, [3, 4], :) with eltype Int64:
    [:, :, 1] =
     5  5
     1  1
    
    [:, :, 2] =
     3  1
     1  1
    
    julia> Pop.parent # original full Pop (now Pop.parent) has been modified
    2×4×2 Array{Int64,3}:
    [:, :, 1] =
     4  3  5  5
     1  1  1  1
    
    [:, :, 2] =
     2  2  3  1
     2  5  1  1