6

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.

Chris Rackauckas
  • 18,645
  • 3
  • 50
  • 81

1 Answers1

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