0

Suppose I have the following 4x4 Array in Julia:

julia> A=rand(4,4)
4×4 Array{Float64,2}:
 0.00624508  0.624399  0.458094  0.341848
 0.303817    0.269487  0.580949  0.534655
 0.748525    0.419411  0.469938  0.659914
 0.730659    0.191461  0.996144  0.74772

And I have another 6x2 Array where each row represents a row-column pair:

julia> B=[ 1 1; 1 3; 2 2; 2 4; 3 1; 3 3]
6×2 Array{Int64,2}:
 1  1
 1  3
 2  2
 2  4
 3  1
 3  3

The first row of B represents the element [1,1] of A, the second row of B represents the element [1,3] of A, and so on. I want to access the elements of A based on the coordinates given by each row of B. In R for example, the command A[B] gives exactly what I want: 0.00624508 0.458094 0.269487 0.534655 0.748525 0.469938 but in Julia, the same command gives

julia> A[B]
6×2 Array{Float64,2}:
 0.00624508  0.00624508
 0.00624508  0.748525
 0.303817    0.303817
 0.303817    0.730659
 0.748525    0.00624508
 0.748525    0.748525

and this is not what I want. Is there a similar way of coding A[B] in Julia, so that I obtain what I obtain in R? Must be applicable to any Array.

1 Answer 1

2

Construct an array of CartesianIndex out of your index pairs:

julia> A[CartesianIndex.(B[:, 1], B[:, 2])]
6-element Array{Float64,1}:
 0.987200021334854    
 0.5261639427155012   
 0.8430528192705655   
 0.5300778835366697   
 0.5044387593056074   
 0.0025132074927423087

This is necessary to distinguish such "point indexing" from "shape indexing", as you observed it (I made those terms up).

Ideally, you would already construct B as such an array, but that is not always feasible, of course.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see! The secret was the CartesianIndex ! I was reading the Julia webpage concerning indexing and saw it but didn't see how I could use it. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.