Re: List Replace Problems
- To: mathgroup at smc.vnet.net
- Subject: [mg59892] Re: List Replace Problems
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Wed, 24 Aug 2005 06:33:00 -0400 (EDT)
- Organization: The Open University, Milton Keynes, U.K.
- References: <deeom3$3rl$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
wesh wrote:
> I want to perform some element by element operations on a class of
> lists. For a given list The operation in a much simplified form can be
> characterized by
>
> a = {1, 3, 5, 7, 9};
> Do[a[[i]] /= i, {i, 1, 5}];
> a
>
> Out[38]=
> {1, 3/2, 5/3, 7/4, 9/5}
>
> Now, however, if I try to define a function to do this for a general
> list, namely,
>
> dlst[u_List] =
> Do[u[[i]] /= i, {i, 1, 5}];
> a = {1, 3, 5, 7, 9};
> dlst[a];
> a
>
> Set::setps:
> ({1, 2, 3, 4, 5}) in assignment of part is not a symbol. ! More ...
>
> Out[39]=
> {1, 3, 5, 7, 9}
>
> I get the above error. It says I'm trying to assign one number to
> another number. Why does Mathematica perform in the first case but
> refuse to in the second.
>
> I tried
>
> b = Do[ReplacePart[a, a[[i]]/i, i], {i, 1, 5}]
>
> but it doesn't even bother to return an error message.
>
>
> How, can I get the desired function?
>
> Thanks,
>
> Wesh
>
Hi Wesh,
You could try a more efficient way to code your function by using a
functional approach. For instance, use *Range* to generate a list of
number form 1 to 5 and divide the list "a" by it.
In[1]:=
a = {1, 3, 5, 7, 9}
b = Range[5]
a/b
Out[1]=
{1, 3, 5, 7, 9}
Out[2]=
{1, 2, 3, 4, 5}
Out[3]=
{1, 3/2, 5/3, 7/4, 9/5}
Now you can write it as a function that is independent of the length of
the list to be divided as follows:
In[4]:=
dlst[u_List] := u/Range[Length[u]];
In[5]:=
a = dlst[a]
Out[5]=
{1, 3/2, 5/3, 7/4, 9/5}
The following link may be of interest:
http://documents.wolfram.com/mathematica/book/section-1.2.3
Hope this helps,
/J.M.