Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #9029

Re: Map onto a column

From Ray Koopman <koopman@sfu.ca>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Map onto a column
Date 2012-03-14 05:45 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <jjpb9p$p9j$1@smc.vnet.net> (permalink)
References <jjmv20$cfr$1@smc.vnet.net>

Show all headers | View raw


On Mar 13, 1:04 am, Sly Pandemia <slypande...@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]]

Back to comp.soft-sys.math.mathematica | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Map onto a column Sly Pandemia <slypandemia@gmail.com> - 2012-03-13 08:04 +0000
  Re: Map onto a column Ray Koopman <koopman@sfu.ca> - 2012-03-14 05:45 +0000
  Re: Map onto a column JasonE <ebaughjason@gmail.com> - 2012-03-14 05:47 +0000
  Re: Map onto a column roby <roby.nowak@gmail.com> - 2012-03-14 05:48 +0000
  Re: Map onto a column dr DanW <dmaxwarren@gmail.com> - 2012-03-16 11:35 +0000

csiph-web