MathGroup Archive 2005

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

Search the Archive

Re: Position function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg55594] Re: Position function
  • From: D Herring <dherring at at.uiuc.dot.edu>
  • Date: Wed, 30 Mar 2005 04:28:55 -0500 (EST)
  • References: <d2b4q9$77c$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

konstantpi at mail15.com wrote:
> suppose i have a List:
> a={{1,3,1,2,1},{5,6,1,1,3,1}}
> how i could know the positions of "1" in every sublist , i could use Position[a
> [[1]],1] and Position[a[[2]],1]
> but i want a one formula to give me {{1,3,5},{3,4,6}}

The Map function is quite handy when doing the same thing to a list of 
entries.  Using unnamed functions inside Map is confusing at first, but 
its highly more compact and less prone to errors for simple cases.

Here, we want each sublist to be processed individually.  My initial 
guess was
Map[Position[#,1]&,a]
Unfortunately, this gave
{{{1}, {3}, {5}}, {{3}, {4}, {6}}}

Here, the undesired depth can easily be fixed with Flatten, so
Map[Flatten[Position[#, 1]]&, a]
yields the desired result.  An equivalent notation is
(Flatten[Position[#1, 1]] & ) /@ a

This second notation is obtained by converting the cell to InputForm.

> the second question:
> using Position[a,1] will give:
> {{1, 1}, {1, 3}, {1, 5}, {2, 3}, {2, 4}, {2, 6}}
> in general how to extract only the second item from every sublist so the output 
> will be;
> {1,3,5,3,4,6}

Similar story here.  Use Map with an unnamed function to only keep the 
second Part of each sublist.
Map[Part[#, 2]&, Position[a, 1]]
or
(#1[[2]] & ) /@ Position[a, 1]


Later,
Daniel


  • Prev by Date: Re: symbolic quaternionic analysis
  • Next by Date: Re: solve question/simplify question
  • Previous by thread: Re: Position function
  • Next by thread: work with graphics and output in a different notebook from the one containing your code