Create a 2D array from a 1D array with reference

Hi
I am trying to use FiniteDiff package to compute a gradient of a function with an N-vector as input and a scalar as output. I need to write the gradient (an N-vector) to a pre-allocated vector (supplied by an optimization solver).

However, the FiniteDiff.finite_difference_jacobian! function will only write to a pre-allocated 1xN 2D array as the Jacobian matrix. How can I wrap the supplied 1D gradient vector by the optimization solver in a 1xN array to trick the finite_difference_jacobian! function into thinking it is getting a reference to a pre-allocated Jacobian matrix of the correct size, without new allocation and copying?

I believe what you are looking for is reshape:

https://docs.julialang.org/en/v1/base/arrays/#Base.reshape

1 Like

reshape does not seem to operate in-place. It creates a new array. Iā€™d like to write to the 1D vector pretending it is a 2D array.

?!?!?! are we reading the same documentation?

The two arrays share the same underlying data, so that the result is mutable if and only if A is mutable, and setting elements of one alters the values of the other.

1 Like

You are right. My bad :slight_smile: