In Julia v0.5, how do you make a function which is like reshape but instead returns a view? ArrayViews.jl has a reshape_view function but it doesn't seem directly compatible with the new view
function. I just want to reshape
u
to some tuple sizeu
where I don't know the dimensions.
Asked
Active
Viewed 1,128 times
6

Chris Rackauckas
- 18,645
- 3
- 50
- 81
-
`reshape` seems to work fine for me for views, and returns a view. what isn't working for you exactly? – Tasos Papastylianou Aug 04 '16 at 21:48
-
I want to reshape an array and get a view of that array out. – Chris Rackauckas Aug 04 '16 at 21:48
-
Ah, right, so you want to pass a *normal* array and get a view out? – Tasos Papastylianou Aug 04 '16 at 21:51
-
Yeah, pass a normal array but a view out where the view makes it act like it's been reshaped, but without allocating. – Chris Rackauckas Aug 04 '16 at 21:52
-
2there are no reallocations during reshaping anyway. you can confirm this with the pointer function – Tasos Papastylianou Aug 04 '16 at 21:55
-
1Oh I just verified it by saving the reshaped value to another variable, changing that variable, and watching it change the first. Wow, I never knew. I probably should've checked that... Post that as an answer so I can mark it. Simple but true. – Chris Rackauckas Aug 04 '16 at 21:58
-
2It's not well known, but `Array` can actually be a view. Try this: `a = rand(6); B = reshape(a, 3, 2); push!(a, 1)` and you'll get an error that reveals this feature. – tholy Aug 04 '16 at 22:23
1 Answers
10
If you reshape a 'view', the output is a reshaped 'view'.
If your initial variable is a normal array, you can convert it to a view 'on the fly' during your function call.
There are no reallocations during this operation, as per your later comment: you can confirm this with the pointer
function. The objects aren't the same, in the sense that they are interpreted as pointers to a different 'type', but the memory address is the same.
julia> A = ones(5,5,5); B = view(A, 2:4, 2:4, 2:4); C = reshape(B, 1, 27);
julia> is(B,C)
false
julia> pointer(B)
Ptr{Float64} @0x00007ff51e8b1ac8
julia> pointer(C)
Ptr{Float64} @0x00007ff51e8b1ac8
julia> C[1:5] = zeros(1,5);
julia> A[:,:,2]
5×5 Array{Float64,2}:
1.0 1.0 1.0 1.0 1.0
1.0 0.0 0.0 1.0 1.0
1.0 0.0 0.0 1.0 1.0
1.0 0.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0

Tasos Papastylianou
- 21,371
- 2
- 28
- 57