Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: reading different locations of a matrix specified by

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113874] Re: reading different locations of a matrix specified by
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Tue, 16 Nov 2010 06:14:38 -0500 (EST)

Nasser,

The simplest and fastest by far is to use Extract:

In[1]:= A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

Out[1]= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

In[2]:= Extract[A, {{1, 1}, {3, 3}}]

Out[2]= {1, 9}


You may want to check out a section in my book where I was addressing a very
similar
problem of efficient extraction of matrix diagonals, for an example of
application of
Extract in a similar setting:

http://www.mathprogramming-intro.org/book/node577.html

Regards,
Leonid



On Tue, Nov 16, 2010 at 1:06 PM, Nasser M. Abbasi <nma at 12000.org> wrote:

> 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: Mathematica 8 docs online now!
  • Next by Date: Re: Using MapAt with Play
  • Previous by thread: Re: reading different locations of a matrix specified
  • Next by thread: does NDSolve have an option equivalent to StoppingTest-> ?