Re: Replace specific element with specific value.

• To: mathgroup at smc.vnet.net
• Subject: [mg99651] Re: Replace specific element with specific value.
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Sun, 10 May 2009 05:16:38 -0400 (EDT)

```On 5/9/09 at 3:22 AM, nick.maj at mssm.edu wrote:

>I tried this code, it gives me right and wrong results spreeded into
>nested lists.

>data = {{0, 2}, {2, x}, {3, 4}, {4, 6}, {6, y}, {8, 9}, {9, z}}

>Table[{#1, #2 + Which[#2 === j, i, #2 =!= j, 0]} & @@@
>data, {i, {xx, yy, zz}}, {j, {x, y, z}}]

>needed output:

>{0, 2}, {2, x+xx}, {3, 4}, {4, 6}, {6, y+yy}, {8, 9}, {9, z+zz}}

>While searching only the second element of each list, if x is found
>add xx and if y is found add yy to it etc.

Why not use pattern matching? That is:

In[1]:= data = {{0, 2}, {2, x}, {3, 4}, {4, 6}, {6, y}, {8, 9}, {9,
z}};

In[2]:= data /. {x -> x + xx, y -> y + yy, z -> z + zz}

Out[2]= {{0, 2}, {2, x + xx}, {3, 4}, {4, 6}, {6, y + yy}, {8,
9}, {9,
z + zz}}

Here, I've manually input the replacement rules which seems fine
for only three variables. If there where a large number of
variables to treat in this manner, I would generate the
replacement rules programatically. Perhaps something like

In[3]:= Rule @@@ (ToExpression[{#, # <> "+" <> # <> #}] & /@ {"x",
"y", "z"})

Out[3]= {x->x+xx,y->y+yy,z->z+zz}

```

• Prev by Date: Re: Plotting in a dynamic environment.
• Next by Date: Re: Manipulate Issue - resend with code
• Previous by thread: Re: Replace specific element with specific value.
• Next by thread: Re: Replace specific element with specific value.