I'm not sure what you are trying to accomplish but here are a couple of fragments which may help.
reshape
can take an optional argument, called pad
, which can be used to provide the 'extra' elements needed when you reshape into an array with more elements than you started with, say from 3x4 to 2x4x2.
You may also be interested in the spread
function which is designed for 'upranking' arrays, that is taking a rank-N array in and putting out a rank-N+1 array. The fragment in your second copy could be rewritten as
array2d = spread(array1d,2,2)
In this example the second argument is the dimension along which to spread the first argument to make the output. The third argument is the number of copies of the input array to make.
PS The call to spread
should perhaps be spread(array1d,1,2)
, I haven't checked it.
EDIT in response to OP's editing of question
The two cases, 1 and 2, are satisfied by spreading across dimensions 2 and 1 respectively. In Fortran
b = spread(a,2,j)
and
b = spread(a,1,j)
Since spread
returns an array with rank 1 greater than the rank of its first argument, it provides the sought-for arbitrary dimensionality. However, since it's so space-consuming to show arrays of rank-3 and above I'm not going to.