# how is an arbitrary dimension "reshaper" turned into a function given a linear index?

i have an arbitrary "reshaping" function which, given a linear sequential array can "reshape" it to 2D or 3D. the order in which the X-dimension, Y-dimension and Z-dimension may all be changed, as well as the size of the X, Y and Z dimensions, may all be changed, at runtime. consequently it is not possible to use static compilers or static allocation.

here is a function that, for the full sequential range, prints out a corresponding (remapped) set of indices:

(xdim, ydim, zdim) = (3, 2, 5)
lims = [xdim, ydim, zdim]
idxs = [0,0,0]
order = [1,0,2]

for idx in range(xdim * ydim * zdim):
new_idx = idxs + idxs * xdim + idxs * xdim * ydim
print new_idx,
for i in range(3):
idxs[order[i]] = idxs[order[i]] + 1
if (idxs[order[i]] != lims[order[i]]):
break
print
idxs[order[i]] = 0


what i actually need is a function which, when it is passed an arbitrary index, returns one (correct) remapped index.

i suppose what i could hypothetically do is have a function that sets up the full array (at startup time), and indexes it. i would however like to see an algorithmic version of the above.

• Welcome to Computer Science! It might be a surprise to you, but your question is off-topic here: we deal with computer science questions, not programming questions. Please see our help on topic. Your question might be on-topic on Stack Overflow. Nov 3, 2018 at 11:03
• interesting, thanks jack. i'm probably going to store the full state. the algorithm itself is unusual: dynamic dimensional reshaping is not something i've seen done before. it's actually to be used in the design of a 3D GPU, to allow contiguous registers containing arbitrary-arranged matrices to be multiplied and added.
– lkcl
Nov 3, 2018 at 11:18
• If you can read the code and translate it to pseudocode, it might become on-topic if you have a specific question about how the algorithm works. By the way, you are supposed to provide a url or reference to the origin of the "reshaping" function if you want to post your question anywhere. Nov 3, 2018 at 11:24
• lists.libre-riscv.org/pipermail/libre-riscv-dev/2018-October/… and lists.libre-riscv.org/pipermail/libre-riscv-dev/2018-October/… where there is a reference to an LLVM discussion about Matrices from Vulkan3D - apologies i appreciate this isn't an "academic" reference!
– lkcl
Nov 7, 2018 at 7:03

If the index of $$(i,j,k)$$ is $$p = i + xj + xyk$$ then you can compute $$i,j,k$$ given $$p$$ as follows:
i = p mod x