There is an operation for which I have long wanted to find a better solution.
Let:
a
be a matrix of dimensions $m\times n$v
be an integer vector of length $n$ with elements drawn from $[1, m]$
For every element $x$ at position $p$ in v
I wish to select the element at row $x$, column $p$ in a
.
Example:
SeedRandom[0]
a = Array[Range[7] 10^# &, 3, 0]
v = RandomInteger[{1,3}, 7]
$\left( \begin{array}{ccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 10 & 20 & 30 & 40 & 50 & 60 & 70 \\ 100 & 200 & 300 & 400 & 500 & 600 & 700 \\ \end{array} \right)$
{3, 3, 2, 1, 1, 3, 1}
Desired output:
{100, 200, 30, 4, 5, 600, 7}
Details:
Although a compiled function is likely to be the fastest approach for packed arrays I want something more general, allowing arrays of mixed types, and ideally optimized for arrays in which each row is a packed array (list) of a different type, e.g.
$\left( \begin{array}{ccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 0.1 & 0.2 & 0.3 & 0.4 & 0.5 & 0.6 & 0.7 \\ \text{a} & \text{b} & \text{c} & \text{d} & \text{e} & \text{f} & \text{g} \\ \end{array} \right)$
I am still interested in seeing the fastest possible compiled function as it may serve as the basis for a general solution as well.
I seek a solution that works well for any shape of array
a
, from $n\gg m$ to square to $m\gg n$, though if compromise is necessary I would optimize for $n > m$.