3
$\begingroup$

I have a 2x2 matrix "M", and a list "ind" containing pairs of indices.

M = {{a, b, c}, {d, f, g}, {h, i, j}};
ind = {{1, 2}, {1, 1}, {3, 1}};

I would like to get the elements of the matrix given by the indices in "ind", in this case:

{b,a,h}

The only way I've found to do this is with MapThread:

MapThread[M[[#1, #2]] &, ind\[Transpose]]

However, the matrices and lists I am using are quite large, and this takes considerable time. Is there a more efficient way to do this? Can this be parallelized (maybe by using ParallelMap, instead of MapThread)?

$\endgroup$
2
  • $\begingroup$ M[[Sequence @@ #]] & /@ ind and Welcome to the Mathematica Stack Exchange. $\endgroup$
    – Syed
    Commented Feb 13, 2023 at 21:43
  • $\begingroup$ This is better than MapThread, thank you @Syed. $\endgroup$ Commented Feb 13, 2023 at 22:24

1 Answer 1

6
$\begingroup$

One way is the following

M = {{a, b, c}, {d, f, g}, {h, i, j}};
ind = {{1, 2}, {1, 1}, {3, 1}};

Now

 Extract[M, ind]

Mathematica graphics

Look up Extract

Also Position is designed to return index location which can be used by Extract which makes it easy. You can use Position and then pass the result directly to Extract without having to worry if it will work or not and this works for lists of different dimensions.

The position specifications used by Extract have the same form as those returned by Position, and used in functions such as MapAt and ReplacePart. »

$\endgroup$
1
  • $\begingroup$ Extract is noticeably better than MapThread, thank you. $\endgroup$ Commented Feb 13, 2023 at 22:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.