Re: replacement rule and sparsearray question

• To: mathgroup at smc.vnet.net
• Subject: [mg71352] Re: replacement rule and sparsearray question
• From: Bill Rowe <readnewsciv at sbcglobal.net>
• Date: Wed, 15 Nov 2006 06:45:03 -0500 (EST)

```On 11/14/06 at 5:06 AM, Arkadiusz.Majka at gmail.com wrote:

>How can I apply a replacement rule to sparse array, e.g

>SparseArray[{1,2,3}]/.{2->222}

>and obtain the same result as for {1,2,3}/.{2->222} (what is
>{1,222,3}.

>I DON'T want to call Normal before.

In this particular example where you know the position of the
element to be replaced, use ReplacePart, i.e.,

In[45]:=
s=SparseArray[Range@5];
d=ReplacePart[s,222,2];
Normal@d

Out[47]=
{1,222,3,4,5}

if you don't know the position of the element to be replaced, it
can be obtained as follows:

In[48]:=
pos = DeleteCases[ArrayRules[s] /.
HoldPattern[{a_} -> 2] :> a, _Rule]

Out[48]=
{2}

Now ReplacePart can be used as above, i.e.

In[49]:=
d=ReplacePart[s,222,pos];
Normal@d

Out[50]=
{1,222,3,4,5}

but if the element to be replaced occurs multiple times, this
last would need to be done as

In[51]:=
d=ReplacePart[s,222,Partition[pos,1]];
Normal@d

Out[52]=
{1,222,3,4,5}

It is also possible to construct a pattern that operates
directly on the SparseArray object. But I think that approach is
a bit more complex than what I've outlined here.
--
To reply via email subtract one hundred and four

```

• Prev by Date: Re: List difference using patterns and substitutions.
• Next by Date: Re: List difference using patterns and substitutions.
• Previous by thread: Re: replacement rule and sparsearray question
• Next by thread: Arithmetic Puzzle (so simple it's hard)