Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65941241/julia-view-to-prevent-production-of-a-new-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...