Chris Rackauckas
Chris Rackauckas

Reputation: 19132

Resizing a matrix

I am trying to come up with a performant way of resizing a matrix in Julia. This matrix is just used as an internal cache for Jacobians inside of some methods, and so its values do not need to be preserved in any order (they will be immediately overwritten). I was thinking about generating a vector directly and working with the matrix being the reshape'd view of that vector. However, Julia then blocks me from resize!ing the vector:

Jvec = zeros(9)
J = reshape(Jvec,3,3))
resize!(Jvec,16)


cannot resize array with shared data
 in resize!(::Array{Float64,1}, ::Int64) at ./array.jl:512
 in include_string(::String, ::String) at ./loading.jl:441
 in eval(::Module, ::Any) at ./boot.jl:234
 in (::Atom.##67#70)() at /home/crackauc/.julia/v0.5/Atom/src/eval.jl:40
 in withpath(::Atom.##67#70, ::Void) at /home/crackauc/.julia/v0.5/CodeTools/src/utils.jl:30
 in withpath(::Function, ::Void) at /home/crackauc/.julia/v0.5/Atom/src/eval.jl:46
 in macro expansion at /home/crackauc/.julia/v0.5/Atom/src/eval.jl:109 [inlined]
 in (::Atom.##66#69)() at ./task.jl:60

and also won't let me resize! the vector with the view gone (with the hope of just creating a new view afterwards):

J = 0
resize!(Jvec,16)

cannot resize array with shared data
 in resize!(::Array{Float64,1}, ::Int64) at ./array.jl:512
 in include_string(::String, ::String) at ./loading.jl:441
 in eval(::Module, ::Any) at ./boot.jl:234
 in (::Atom.##67#70)() at /home/crackauc/.julia/v0.5/Atom/src/eval.jl:40
 in withpath(::Atom.##67#70, ::Void) at /home/crackauc/.julia/v0.5/CodeTools/src/utils.jl:30
 in withpath(::Function, ::Void) at /home/crackauc/.julia/v0.5/Atom/src/eval.jl:46
 in macro expansion at /home/crackauc/.julia/v0.5/Atom/src/eval.jl:109 [inlined]
 in (::Atom.##66#69)() at ./task.jl:60

Any insight into how to accomplish this without fully re-allocating the matrix each time is helpful. Thanks in advance.

Upvotes: 4

Views: 1530

Answers (2)

tholy
tholy

Reputation: 12179

You're treading on somewhat dangerous territory (that warning is there for a reason), but if instead of calling reshape(Jvec, 3, 3) you do

J = Base.ReshapedArray(Jvec,(3,3), ())

then it may work as you are hoping.

Upvotes: 6

Kristoffer Carlsson
Kristoffer Carlsson

Reputation: 89

julia> J = rand(3,3);

julia> Jvec = vec(J);

julia> resize!(Jvec, 4*4);

julia> J = reshape(Jvec, (4,4));

julia> Jvec = vec(J);

julia> resize!(Jvec, 5*5);

julia> J = reshape(Jvec, (5,5))

etc works.

Upvotes: 4

Related Questions