3

I'm curious if anyone recalls the decode () function in APL? It was useful to translate between dimensions in an n-dimensional array and a flattened equivalent.

For example, if I had a 4 dimensional array, I could use decode as follows to derive the location in a flattened file:

A = 4 x 5 x 2 x 11 is a 4-d array
B = 440 element flattened version of A
4 5 2 11 decode 1 2 1 3 = 110 + 44 + 11 + 3 = 168th element of B

I recall that I had to add ±1 depending on index root.

I should note...decode is quite easy. It's actually the encode () equivalent (to move from a flat file index back to the array indices) that is useful to me. So how to move from the 168th element back to [1, 2, 1, 3]?

Adám
  • 6,573
  • 20
  • 37
C. Cooney
  • 471
  • 5
  • 19
  • his question needs a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/). Please see [How To Ask Questions The Smart Way](http://www.catb.org/~esr/faqs/smart-questions.html). Always provide a complete [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example "Minimal Reproducible Example"). – itprorh66 Feb 01 '22 at 15:12
  • 1
    All you need to do to convert from a flat index to a multi-dimensional index is express the flat index using the mixed radix given by the array (matrices are 2D, your is a 4D *array*). – Adám Feb 01 '22 at 15:25
  • Thanks Adam. You are correct in your observations. Edited. – C. Cooney Feb 01 '22 at 15:37

1 Answers1

1

While I don't know Python, I do know APL, and based on that knowledge, I think these methods will do the trick:

Converting from array indices to flat index

arrayShape = [4, 5, 2, 11]
strides = [5×2×11, 2×11, 11, 1] = [110, 22, 11, 1] 
arrayIndex = [1, 2, 1, 3]
flatIndex = ∑[1×110, 2×22, 1×11, 3×1] = 168

Converting from flat index to array indices

arrayShape = [4, 5, 2, 11]
strides = [5×2×11, 2×11, 11, 1] = [110, 22, 11, 1] 
flatIndex = 168
How many times can we subtract 110? 1, using 110 with remainder 58
How many times can we subtract  22? 2, using  44 with remainder 14
How many times can we subtract  11? 1, using  11 with remainder 3
How many times can we subtract   1? 3, using   3 with no remainder
arrayIndex = [1, 2, 1, 3]
Adám
  • 6,573
  • 20
  • 37