Re: Part
- Subject: [mg2910] Re: [mg2890] Part
- From: ptk at imada.ou.dk (Peder Thusgaard Ruhoff)
- Date: 9 Jan 1996 04:35:06 -0600
- Approved: usenet@wri.com
- Distribution: local
- Newsgroups: wri.mathgroup
- Organization: Wolfram Research, Inc.
- Sender: mj at wri.com
On Thu, 4 Jan 1996, Hans Steffani wrote:
> w={{1,2,3},{4,5,6},{7,8,9}}
> npos={2,1}
>
> npos is the position of the element I need.
>
> w[[npos]]
>
> does not work, as it returns the second and the first
> line.
>
> w[[ npos[[1]],npos[[2]] ]]
>
> does the wanted thing, but I would prefer a shorter and
> more general way.
>
> Hans Friedrich Steffani
Dear Hans Steffani,
There are several ways to solve your problem.
1. Using Sequence:
==================
In[1]:= w = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
In[2]:= npos = {2, 1};
In[3]:= w[[Sequence @@ npos]]
Out[3]= 4
In[4]:= Timing[Do[w[[Sequence @@ npos]], {10000}]]
Out[4]= {4.05 Second, Null}
2. Using Fold:
==============
In[5]:= Fold[Part, w, npos]
Out[5]= 4
In[6]:= Timing[Do[Fold[Part, w, npos], {10000}]]
Out[6]= {2.46667 Second, Null}
3. Defining a new function Index:
=================================
In[7]:= Index /: Part[x_, Index[n__]] := Part[x, n]
In[8]:= npos = Index[2, 1]
Out[8]= Index[2, 1]
In[9]:= w[[npos]]
Out[9]= 4
In[10]:= Timing[Do[w[[npos]], {10000}]]
Out[10]= {4.03333 Second, Null}
All calculations done using a SUN sparc10.
I hope this helps or at least gives you some ideas.
Peder
------------------------------------------------------------------------------
Peder Thusgaard Ruhoff Phone: (+45) 66 15 86 96, ext. 2411
Dept. of Mathematics and Computer Science Fax: (+45) 65 93 26 91
Odense University, Campusvej 55 Email: ptk at imada.ou.dk
DK-5230 Odense M, DENMARK
"It is important for him who wants to discover not to confine himself
to one chapter of science, but to keep in touch with various others."
- Jacques Hadamard
------------------------------------------------------------------------------