MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

reading different locations of a matrix specified by indices list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113866] reading different locations of a matrix specified by indices list
  • From: "Nasser M. Abbasi" <nma at 12000.org>
  • Date: Tue, 16 Nov 2010 05:06:11 -0500 (EST)
  • Reply-to: nma at 12000.org

Given a matrix A, and list of locations withing the matrix,
where each location is given by {i,j} entry, I wanted to
find the most efficient and clear way to obtain the entries
in the matrix by these locations.

I wanted to ask the experts here what they think of this
method, and if they can suggest a better way.

Example, given

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

and wanted to obtain the entries at say {1,1} and {3,3},
which will be 1 and 9 in this example. So I first made a
list of the locations :

pos={ {1,1},{3,3}};

Then typed

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

and got back

{1,9}

So, this seems to work.

Any suggestion of may be of a more 'obvious' or better way?

fyi, in another system, I do the above as follows (just for
comparison)

----------------------
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
----------------------

I am happy with the Mathematica method, once I figure
out how to do it, the trick for me was to think functional :)

Both ways in both systems are about the same order of
complexity and length.

--Nasser


  • Prev by Date: Re: Simplification question in Mathematica 7
  • Next by Date: Varying plot symbols according to additional criteria in Mathematica
  • Previous by thread: Re: reading different locations of a matrix specified by indices
  • Next by thread: Varying plot symbols according to additional criteria in Mathematica