2.20 extract values from matrix given their index

Given a matrix A, and list of locations within the matrix, where each location is given by \(i,j\) entry, find the value in the matrix at these locations

Example, given

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

obtain the entries at \(1,1\) and \(3,3\) which will be \(1\) and \(9\) in this example.

Mathematica

mat={{1,2,3}, 
     {4,5,6}, 
     {7,8,9}} 
 
pos = { {1,1},{3,3}}; 
Map[ mat[[Sequence@@ # ]] & , pos ]
 

   {1,9}
 

Another method (same really as above, but using Part explicit)

Map[Part[A, Sequence @@ #] &, pos]
 

{1,9}
 

 

Matlab

A=[1 2 3; 
   4 5 6; 
   7 8 9]; 
I=[1 3];  % setup the I,J indices 
J=[1 3]; 
A(sub2ind(size(A),I,J))
 

ans = 
     1     9
 

 

Maple

A:=Matrix([[1,2,3],[4,5,6],[7,8,9]]); 
loc:=[[1,1],[3,3]]; 
map(x->A[op(x)],loc);
 

    [1, 9]