Search code examples
indexingjuliamatrix-indexing

julia index matrix with vector


Suppose I have a 20-by-10 matrix m

and a 20-by-1 vector v, where each element is an integer between 1 to 10.

Is there smart indexing command something like m[:,v]

that would give a vector, where each element i is element of m at the index [i,v[i]]?


Solution

  • No, it seems that you cannot do it. Documentation (http://docs.julialang.org/en/stable/manual/arrays/) says:

    If all the indices are scalars, then the result X is a single element from the array A. Otherwise, X is an array with the same number of dimensions as the sum of the dimensionalities of all the indices.

    So, to get 1d result from indexing operation you need to have one of the indices to have dimensionality 0, i.e. to be just a scalar -- and you won't get what you want then.

    Use comprehension, as proposed in the comment to your question.