MathGroup Archive 2012

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

Search the Archive

Re: Map onto a column

  • To: mathgroup at smc.vnet.net
  • Subject: [mg125453] Re: Map onto a column
  • From: Ray Koopman <koopman at sfu.ca>
  • Date: Wed, 14 Mar 2012 00:41:27 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <jjmv20$cfr$1@smc.vnet.net>

On Mar 13, 1:04 am, Sly Pandemia <slypande... at gmail.com> wrote:
> Is there a neat way to map a function onto a specific column in an
> array?
>
> For example if I have
>
> a = {{1,2,3},{4,5,6},{7,8,9}}
>
> and I want to map f onto the second element in each row. I would
> normally use
>
> b = Map[MapAt[f,#,2]&,a]
>
> but this seems a bit awkward. I would expect to be able to use
>
> b = MapAt[f,a,{All,2}]
>
> but this appears to be illegal syntax.
>
> Is there any way to do what I want with a single Map/MapAt function?

When I started using Mathematica I avoided abbreviations such as
& /@ @ @@ @@@ /; /. //. etc, but now I prefer them to the long forms
in most situations. Here is your normal way, written more compactly,
which IMHO makes it not awkward:

  b = MapAt[f,#,2]&/@a

The remaining methods work only if f is Listable;
this step can be omitted if f is already Listable:

  SetAttributes[f,Listable]

If a has many rows then this can be much faster than your normal way:

  b = Transpose@MapAt[f,Transpose@a,2]

(From time to time I've been tempted to put T=Transpose in my init.m,
so I could write things like T@MapAt[f,T@a,2].)

This changes column 2 of a in place and returns the new column 2:

  a[[All,2] = f@a[[All,2]]

This sets b and returns the new column 2:

  b = a; b[[All,2]] = f@b[[All,2]]



  • Prev by Date: How can I make a sequence that includes lists?
  • Next by Date: Re: Trouble Getting Graphic Primitives in a Module to Display with Show Command
  • Previous by thread: Re: Map onto a column
  • Next by thread: Re: Map onto a column