MathGroup Archive 2009

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

Search the Archive

Re: Re: ReplacePart except first element?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg102144] Re: [mg102085] Re: ReplacePart except first element?
  • From: DrMajorBob <btreat1 at austin.rr.com>
  • Date: Thu, 30 Jul 2009 05:35:12 -0400 (EDT)
  • References: <h4m4ar$eah$1@smc.vnet.net> <200907290908.FAA19525@smc.vnet.net>
  • Reply-to: drmajorbob at bigfoot.com

Works for me:

h[x_, a_] := ReplacePart[x, a -> x[[a]] + 1]

h[{1, 2, 3}, 1]

{2, 2, 3}

h[{1, 2, 3}, 2]

{1, 3, 3}

h[{1, 2, 3}, 3]

{1, 2, 4}

Bobby

On Wed, 29 Jul 2009 04:08:40 -0500, Ray Koopman <koopman at sfu.ca> wrote:

> On Jul 27, 11:03 pm, mokambo <alexandrepassosalme... at gmail.com> wrote:
>> I was trying to modify a list by adding 1 to a certain element.
>> I can't understand the following result:
>>
>> h[x_List, a_Integer] := ReplacePart[x, a -> x[[a]] + 1]
>>
>> h[{1, 2, 3}, 2] gives {,3,3} (what happened to the first element?) but
>> h[{1, 2, 3}, 1] gives {2,2,3} as expected.
>>
>> Eventually I changed to:
>>
>> h[x_List, a_Integer] := MapAt[Function[y, y + 1], x, a]
>>
>> but the ReplacePart version still puzzles me.
>> Is it because ReplacePart creates a copy instead of altering inline
>> like x[[a]] = val does?
>
> I don't know why
>
>   h[x_,a_] := ReplacePart[x, a -> x[[a]] + 1]
>
> gave you what you posted. I get an error message
> and then the input with the Rule evaluated:
>
>   h[{1,2,3}, 1]
>
>   ReplacePart::argt:
>    ReplacePart called with 2 arguments; 3 or 4 arguments are expected.
>
>   ReplacePart[{1,2,3}, 1 -> 2]
>
> Here are three versions, all of which do what you want:
>
>   h[x_,a_] := MapAt[#+1&, x, a]
>
>   h[x_,a_] := ReplacePart[x, x[[a]]+1, a]
>
>   h[x_,a_] := x /. (x[[a]] -> x[[a]] + 1)
>



-- 
DrMajorBob at bigfoot.com


  • Prev by Date: Re: ViewVector->{0,0,0}
  • Next by Date: Re: bvdae error when using NDSolve for initial value problem
  • Previous by thread: Re: ReplacePart except first element?
  • Next by thread: Re: Re: ReplacePart except first element?