Fengyang's reshape((@view x[1:6]), (3, 2)) will work well and will be 
essentially cost-free since reshape creates a view, and a view of a view is 
still just a view (no copy). Another way to write it is 
reshape(view(x,1:6), (3, 2)). For example:

function f(t,u,du)
  x = reshape(view(x,1:6), (3, 2))
  # Use x and u[7], u[8], u[9], and u[10] to write directly to du
  nothing
end

 should be a good way to write the function for Sundials.jl, 
DifferentialEquations.jl, ODE.jl (after the iterator PR).

On Sunday, October 2, 2016 at 5:43:01 AM UTC-7, Alexey Cherkaev wrote:
>
> I have the model where it is convenient to represent one of the variables 
> as a matrix. This variable, however, is obtained as a solution of ODEs 
> (among other variables). I'm using Sundials to solve ODEs and 
> `Sundials.cvode` requires the ODE RHS function to take a vector. So, it 
> seems logical to pack the variables into a vector to pass to `cvode` and 
> unpack them for more convenient use in my code.
>
> For example, consider `x = fill(1.0, 10)` and the first 6 entries are 
> actually a matrix of size 3x2, other 4: other variables. So, I can do `s = 
> reshape(x[1:6], (3,2))`. However, this creates a copy, which I would want 
> to avoid. And I couldn't find a way to do the view-reshaping by applying 
> `view()` function or doing `SubArray` directly. For now I settle on to 
> using indices of the form `(i-1)*M + j +1` to retrieve `s[i,j] = x[(i-1)*M 
> + j +1]`. But, (1) julia's 1-based arrays make it awkward to use this 
> notation and (2) matrix (not element-wise) operations are not available.
>

Reply via email to