Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1996
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1996

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

Search the Archive

Re: Part

  • To: mathgroup at smc.vnet.net
  • Subject: [mg2910] Re: [mg2890] Part
  • From: Peder Thusgaard Ruhoff <ptk at imada.ou.dk>
  • Date: Tue, 9 Jan 1996 02:18:33 -0500

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


==== [MESSAGE SEPARATOR] ====


  • Prev by Date: Re: Question
  • Next by Date: 2.2.3 Running under Win 95
  • Previous by thread: Re: Part
  • Next by thread: Re: Part