1
$\begingroup$

If I have an array of sets of points such as

pts = {{2,4},{1,3},{5,7}}

Is there any super short command to use those pairs to output their respective elements in a matrix in one felt swoop without loops?

Also, is there a way to output elements of an array corresponding to just the first or just the second element in all pairs? so given an array

array = {1,2,3,4,5,6,7,8}

output only

{2,1,5}

corresponding to the first element in each pair in pts

$\endgroup$
  • 2
    $\begingroup$ Take a look at Part, Extract, Span and friends. array[[pts[[All, 1]]]]. $\endgroup$ – Kuba Jun 17 '15 at 17:00
  • $\begingroup$ @Kuba, perfect, thank you! $\endgroup$ – Raksha Jun 17 '15 at 17:11
  • $\begingroup$ @Kuba ups! Haven't read your comment in time. Sorry $\endgroup$ – Dr. belisarius Jun 17 '15 at 17:25
  • $\begingroup$ @belisarius I don't think you should be, why? :) $\endgroup$ – Kuba Jun 17 '15 at 17:32
  • $\begingroup$ @Kuba I used Extract in my answer and you suggested that a pair of minuts before in your comment. Nothing to worry about, I guess! $\endgroup$ – Dr. belisarius Jun 17 '15 at 17:48
4
$\begingroup$
SeedRandom[42];
pts = {{2, 4}, {1, 3}, {5, 7}};
a = RandomInteger[{1, 10}, {7, 7}]
Extract[a, pts]
(* {2, 9, 10} *)

Grid[a, Background -> {None, None, Thread[pts -> Red]}]

Mathematica graphics

| improve this answer | |
$\endgroup$
  • $\begingroup$ great! thank you! $\endgroup$ – Raksha Jun 17 '15 at 17:02
  • $\begingroup$ Haha, very fancy XD $\endgroup$ – Raksha Jun 17 '15 at 17:12

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.