       Re: Strange Behaviour of ReplaceAll with Subscript (A bug or what?)

• To: mathgroup at smc.vnet.net
• Subject: [mg113334] Re: Strange Behaviour of ReplaceAll with Subscript (A bug or what?)
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Sun, 24 Oct 2010 06:04:45 -0400 (EDT)

```On 10/23/10 at 7:06 AM, thomasgdowling at gmail.com (Thomas Dowling)
wrote:

>I have come across some strange behaviour with ReplaceAll when
>creating subscripted variables, which I am not able to explain.

>The Problem:

>I have lists like the following:

>list1 = Partition[Range, {3}]

>list2 = Partition[Range, {3}]

>I wish to convert to a list of indexed variables which I do as
>follows:

>replist={Subscript[a,x],Subscript[a,y],Subscript[a,z]};

>list1/.{x_,y_,z_}-> replist

>This produces the expected output

>{{Subscript[a, 1],Subscript[a, 2],Subscript[a, 3]},{Subscript[a,
>4],Subscript[a, 5],Subscript[a, 6]}}

>list3/.{x_,y_,z_}-> replist

>However, **list2** produces the following

>list2/.{x_,y_,z_}-> replist

>{Subscript[a, {1,2,3}],Subscript[a, {4,5,6}],Subscript[a, {7,8,9}]}

>Is this a bug or is such behaviour expected (and if so, what am I
>missing?)

No, it is not a bug. The problem is the pattern {x_,y_,z_}
matches any list of three items. A 3 x 3 list of integers is a
list of three lists each having 3 integers. So, the pattern
matches the top level list. For any n x 3 array where n is not
3, the pattern can only match the sublists and will work as you
expect. A solution is to make the pattern match more restrictive.

For example, using the pattern {x_Integer,y_,z_} restricts the
match to a list of three elements where the first is an integer.
With this pattern

In:= list2 /. {x_Integer, y_, z_} -> replist

Out= {{Subscript[a, 1], Subscript[a, 2], Subscript[a, 3]},
{Subscript[a, 4], Subscript[a, 5], Subscript[a, 6]},
{Subscript[a, 7], Subscript[a, 8], Subscript[a, 9]}}

The desired result is obtained.

Another way to achieve the same result would be to use a level
specification with Map. For example,

In:= Map[Subscript[a, #] &, list2, {2}]

Out= {{Subscript[a, 1], Subscript[a, 2], Subscript[a, 3]},
{Subscript[a, 4], Subscript[a, 5], Subscript[a, 6]},
{Subscript[a, 7], Subscript[a, 8], Subscript[a, 9]}}

This solution will work for any m X n array and ragged arrays.

```

• Prev by Date: How to detect 'bad' characters in expressions in the notebook?
• Next by Date: Re: Strange Behaviour of ReplaceAll with Subscript (A bug or what?)
• Previous by thread: Strange Behaviour of ReplaceAll with Subscript (A bug or what?)
• Next by thread: Re: Strange Behaviour of ReplaceAll with Subscript (A bug or what?)