3
$\begingroup$

I have a list of lists e.g: c=Table[i+j,{i,5},{j,5}] and a={1,2,3};b={3,2,5}; Now I want to access the elements of c from a,b. Eg. I want c[[a[[1]],b[[1]]]],c[[a[[2]],b[[2]]]],c[[a[[3]],b[[3]]]] etc. I have a very big c, a,b lists. All I want is to access the c elements just like above from a,b. Is there any way I can do this?

$\endgroup$
  • $\begingroup$ Does one of the answers below answer your question? If so, please accept one by clicking the grey checkmark next to the answer! If not, please explain why not by commenting on the answers! $\endgroup$ – march Oct 19 '15 at 5:23
4
$\begingroup$

From J. M. is back:

Extract[c, Transpose[{a, b}]]

Here's some other ways:

Table[c[[a[[i]], b[[i]]]], {i, 1, Length@a}]
c[[##]] & @@@ Transpose[{a, b}]
MapThread[c[[##]] &, {a, b}]
Outer[c[[##]] &, a, b] // Diagonal

By the way, don't use the last one. It does way too many unnecessary calculations.

$\endgroup$
  • $\begingroup$ Another one for your list: Extract[c, Transpose[{a, b}]] $\endgroup$ – J. M. is away Oct 11 '15 at 2:12
  • $\begingroup$ @J.M.isback. Wasn't familiar with that one! Thanks. (For some reason I've avoided Extract.) By the way, does the "is back" mean that you have a computer again? $\endgroup$ – march Oct 11 '15 at 2:13
  • 1
    $\begingroup$ Yes, yes, I do. Finally. :) $\endgroup$ – J. M. is away Oct 11 '15 at 2:14
3
$\begingroup$

Use Inner

c = Table[i + j, {i, 5}, {j, 5}]

(*  {{2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {4, 5, 6, 7, 8}, {5, 6, 7, 8, 
  9}, {6, 7, 8, 9, 10}}  *)

a = {1, 2, 3}; b = {3, 2, 5};

Inner[c[[#1, #2]] &, a, b, List]

(*  {4, 4, 8}  *)

Or slightly simplified

Inner[c[[##]] &, a, b, List]


c = Array[x, {5, 5}];

Inner[c[[#1, #2]] &, a, b, List]

(*  {x[1, 3], x[2, 2], x[3, 5]}  *)

Or again, slightly simplified

Inner[c[[##]] &, a, b, List]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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