Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2007
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2007

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

Search the Archive

Re: Map function which adds last two numbers of a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg73557] Re: [mg73530] Map function which adds last two numbers of a list
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Wed, 21 Feb 2007 06:07:41 -0500 (EST)
  • References: <200702210646.BAA18238@smc.vnet.net>

On 21 Feb 2007, at 07:46, Christopher Pike wrote:

>
> Hi,
>   Consider this:
>
> z = {{1,4,5,6},{7,8,9,1},{1,2,4,3}}
>
> I'd like to Map a function onto z which would replace the last two  
> items
> with their sum:
>
> {{1,4,11},{7,8,10},{1,2,7}}
>
> I could easily use the Table command to construct this new table,  
> but it
> would be nicer if I new how to Map some function on z that would  
> produce
> the same result.
>
> Any suggestions.
>
> Thanks, Chris Pike
>

In my opinion, in a programming language like Mathematica's  just  
like in mathematics  it is a wrong approach to start with a method  
(in your case using the Map function) and then attempt to solve a  
problem using this prescribed method. The right approach is the other  
way round; you start with a problem and then try to find the most  
suitable method. Mathematica offers you a large variety of methods,  
and there is no need at all to limit onself just to some of them.  
Thus, in this case the most obvious thing that comes to my mind is:


z = {{1,4,5,6},{7,8,9,1},{1,2,4,3}}


z /. {a___, b_, (c_)?NumericQ} -> {a, b + c}


{{1, 4, 11}, {7, 8, 10}, {1, 2, 7}}

Of course you could to the same using Map. for example

(Flatten[{Take[#1, 2], Plus @@ Take[#1, -2]}] & ) /@ z


{{1, 4, 11}, {7, 8, 10}, {1, 2, 7}}

but why is this better?


Andrzej Kozlowski



  • Prev by Date: ToMatlab limitations
  • Next by Date: Re: Re: Issue
  • Previous by thread: Re: Map function which adds last two numbers of a list
  • Next by thread: RE: Map function which adds last two numbers of a list