MathGroup Archive 2005

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

Search the Archive

Re: List Replace Problems

  • To: mathgroup at smc.vnet.net
  • Subject: [mg59847] Re: List Replace Problems
  • From: David Bailey <dave at Remove_Thisdbailey.co.uk>
  • Date: Wed, 24 Aug 2005 06:30:13 -0400 (EDT)
  • 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,

First, your code would really become a lot more compact (and efficient!) 
if you used functional constructs, but since not everyone is comfortable 
with this style of programming, let's look at your code as is.

The basic problem is that operations that alter the contents of a list 
(as opposed to, say, creating a new list) can only work if that list is 
assigned to a variable - 'a' in your case. However, when you call dlst 
you actually pass the value of 'a', which is a list - so it is invalid 
to try to destructively alter it.

There are many ways round this. One would be to assign u to a local 
variable, v (say) inside dlst, manipulate that, and then return the 
whole list as the result. Of course, if your list is really vast, maybe 
you don't want to do that because it involves taking a copy.

My general advice would be to read a book on Mathematica programming or 
go on a course. It is all too easy to get into very bad programming 
habits and struggle!

David Bailey
http://www.dbaileyconsultancy.co.uk


  • Prev by Date: Re: Re: How to free memory?
  • Next by Date: Re: Does ContourPlot behave correctly?
  • Previous by thread: Re: List Replace Problems
  • Next by thread: Re: List Replace Problems