MathGroup Archive 2010

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

Search the Archive

Re: newbie list question

  • To: mathgroup at smc.vnet.net
  • Subject: [mg114990] Re: newbie list question
  • From: Helen Read <readhpr at gmail.com>
  • Date: Tue, 28 Dec 2010 06:46:42 -0500 (EST)
  • References: <if70bt$330$1@smc.vnet.net>

On 12/26/2010 4:02 AM, Gareth Edwards wrote:
> Hi,
>
> Liking Mathematica a lot, but struggling with the early part of the learning curve, i.e. don't know what I don't know...
>
> What would be the neatest syntax for finding the first location of elements from one list in another? For example:
>
> listA = { 4,5,8,2,6,4 }
> listB = { 8,4,2 }
>
>
> I would like a function to return {3,1,4} in this case (the first location in A of each element in B)
>
> Many thanks!
>

The basic idea is to use Position to find the position of one element at 
a time, then Map it across listB.

listA = {4, 5, 8, 2, 6, 4};
listB = {8, 4, 2};

See what this does:

Position[listA, 4]

You want only the first occurrence, so look at the Documentation for 
Position, where you will find what you need here:

	Position[expr,pattern,levelspec,n]
gives the positions of the first n objects found.

We want the first position, so n=1. We need a level specification (how 
deep in a nested list), which is 1 since you have no nesting. So this:
	
Position[listA, 4, 1, 1]

Now, we want to apply this to each element of listB, instead the single 
element 4 used in the example above. One way to do this is to write an 
auxiliary function that does the operation you want on a single element, 
call it x. Then Map this function across listB.

f[x_] := Position[listA, x, 1, 1];

Map[f, listB]

Finally, use Flatten to remove the extra braces:

Flatten[Map[f, listB]]


Once you get how that all works, try using a pure function to do it in 
one fell swoop:


Flatten[Map[Position[listA, #, 1, 1] &, listB]]


-- 
Helen Read
University of Vermont


  • Prev by Date: typesetting problems or bugs? need a professional stylesheet
  • Next by Date: Re: Compiling in Mathematica 8
  • Previous by thread: Re: newbie list question
  • Next by thread: Re: newbie list question