Access the element at a specific position of a matrix in Julia

Hi, I know how to access the element at a specific position of a matrix. For example,

m = [1 2 3; 4 5 6] # m is a 2 by 3 matrix
m[1,2]                  # m[1,2] would return the element at position (1,2), which is number 2
m[(1,2)]                # m[(1,2)] would not work

I’m reading some code, and get into the following confusing point.

indices = [ ( m.v[i], m.v[j] ) for (i,j) in m.e   ]

m.w[ indices[i] ]

indices is a vector of tuples, and m.w is a matrix. This would not work, right? based on the similar reasons as the above, or did I miss something?

You’re correct, this won’t work. You can use CartesianIndex for exactly this purpose though:

indices = [ CartesianIndex(m.v[i], m.v[j]) for (i,j) in m.e   ]
1 Like

And m[(1,2)...] works.

Any ideas on why? :smiley:

Because there’s no method defined for indexing a matrix with a tuple. But if you unpack the tuple with ..., it’s the same as m[1,2]