< Back to IRCAM Forum

Subindex Access to a table

I have a table defined (for example) as follows:

$t := [$x | $x in 1 … 20]

I would like to access subindexes as another table, using a table of index. For example $index := [0, 2, 4]. Doing $t[($index)] is not possible.

Is there an easy way for doing this?

Ps: If you want to access the first N elements of your table you can use the internal @lace function as @lace($t, 3). Just discovered and thought to share… .

I am not sure to understand what you need.

If you need to build a tab made of the elements whose indices appear in $index, then you can write
$t2 := [ $t[$i] | $i in $index ]
The iterator $i in $index specifies that $i will take all the values in the tab $index (in the right order). So this tab comprehension is equivalent to
$t2 := [ $t[$index[$i]] | $i in 0 … @size($index) ]

But I can understand your question in another way: if $t is a multidimensional tab (that is, a tab of tabs), then $index can be interpreted as a (computed) sequence of indices to access one element nested in $t. For instance, here you want to access to $t[0, 2, 4] (obviously, this will fail with vector $t). You cannot write the previous expression nor $t[$index[0], $index[1], $index[2]] because you don’t known a priori the size of $index. In this case, you can write a recursive function to get the specified element:

@fun_def get($t, $i)  
{  
   if (@empty($i)   
   { $t }  
   else  
   { @get($t[$i[0]], @cdr($i)) }  
     
}

and then
@get($t, $index)

Thanks @giavitto… . What I needed was $t2 := [ $t[$i] | $i in $index ] to create a new table composed of indexes $index in table t. Powerful indeed! :slight_smile: