PokeLu
PokeLu

Reputation: 847

Julia accessing specific Matrix elements using vectors as indexes

Suppose I have a 4*2 matrix as follows:

a = [1 2; 3 4; 5 6; 7 8]
4×2 Matrix{Int64}:
 1  2
 3  4
 5  6
 7  8

I want to access the matrix using a vector specifying which element I want to access in each column. In NumPy from python, I would do the following command:

a[[1,3], [1,2]]

# expected output:
1×2 Matrix{Int64}:
 1(as a[1,1])  6(as a[3,2])

but in Julia, I got the following matrix:

2×2 Matrix{Int64}:
 1  2
 5  6

How can I do it in an julia way?

Upvotes: 2

Views: 1351

Answers (2)

Dan Getz
Dan Getz

Reputation: 18217

UPDATE: Inspired by DNF answer:

julia> a[CartesianIndex.([1 3], [1 2])]
1×2 Matrix{Int64}:
 1  6

seems to me the right balance of clarity and similarity to OP.

ORIGINAL answer:

Maybe not the optimal way, but:

[a[x...] for x in [[[1,1]] [[3,2]]]]

works.

Note that this returns a row vector, like in the OP. In Julia there is a difference between a vector and a matrix. A matrix with one row or one column is not the same as a vector.

The [[]] notation is to let hcat handle vector elements correctly. If a vector output is good enough, then: [[1,1],[3,2]] is enough.

Upvotes: 2

DNF
DNF

Reputation: 12644

The syntax a[i, j] is syntax sugar for getindex(a, i, j). You can broadcast getindex to get the desired behavior (unfortunately, you cannot broadcast the [] syntax itself):

getindex.(Ref(a), [1,3], [1,2])

You must protect a itself against being broadcasted, by wrapping it in a Ref.

Upvotes: 2

Related Questions