I have a matrix `A`

and a row index vector R and a column index vector C.

I want to get a vector from `A`

as `[A[R[1], C[1]], A[R[2], C[2]], ...]`

.

For instance, with `R=[2, 4], C=[3, 1]`

, I want `[A[2, 3], A[4, 1]]`

.

Is there any built-in mechanism for this kind of indexing? `A[R, C]`

will not work.

You may broadcast `getindex`

as `getindex.(Ref(A), rowinds, colinds)`

5 Likes

In this specific case, I recommend the `getindex`

broadcast suggested above. In a more general or complicated situation, consider using the `CartesianIndex`

type. For example,

```
julia> R = [2, 4]; C = [3, 1]; A = [10i+j for i in 1:4, j in 1:4]
4×4 Matrix{Int64}:
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
julia> CartesianIndex.(R, C)
2-element Vector{CartesianIndex{2}}:
CartesianIndex(2, 3)
CartesianIndex(4, 1)
julia> A[CartesianIndex.(R, C)]
2-element Vector{Int64}:
23
41
```

5 Likes

Not a recommendation, just a different view angle using LinearAlgebra.jl:

```
diag(view(A, R, C))
```

With TensorCast.jl, we can take a non-allocating view along the diagonal:

```
using TensorCast
@cast v[i] := view(A, R, C)[i,i]
```

this view is equivalent to writing:

```
V = view(A, R, C)
view(V, diagind(V))
```

```
r,c=size(A)
@. A[(C-1)*r+R]
```

1 Like