Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of encode / decode from APL in Python

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]?

like image 798
C. Cooney Avatar asked Feb 18 '26 07:02

C. Cooney


1 Answers

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]
like image 91
Adám Avatar answered Feb 19 '26 19:02

Adám



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!