MathGroup Archive 2000

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

Search the Archive

Re: Set in Scan

Johannes Ludsteck schrieb:
> Dear MathGroup members
> I have to do replacements in very long lists. An efficient way to do
> this is to use
> x[[index]]=newElement.
> This, however, doesn't work if I want to do replacements for a set of
> lists. If I try to replace the third element in the lists v1, v2 and v3 by
> typing
> Scan[#[[3]] = newElement &, {v1,v2,v3}]
> I get the error message
> Set::setps: #1 in assignment of part is not a symbol.

Hallo Johannes,

the problem with your expression is to get the symbols v1,...
unevaluated into the lhs of Set. There are two points where evaluation
occurs, first at the rhs of Scan (or Map) where the list {v1,v2,v3} and
then recursively v1,... are evaluated. You can suppress that by wrapping
the list with Unevaluated. The second is the evaluation of #1 before
Function inserts the argument at the lhs of Set. This can be avoided by
specifing the argument HoldFirst for evaluation of Function:

In[8]:= allv = {v1, v2, v3} = Table[Random[], {3}, {4}]
{{0.308624, 0.0113816, 0.452114, 0.100156}, 
 {0.368705, 0.44588, 0.878839, 0.736246}, 
 {0.71764, 0.18652, 0.667573, 0.338795}}

Scan[Function[sym, sym[[3]] = "-XXX-", {HoldFirst}], 
  Unevaluated[{v1, v2, v3}]]

In[10]:= {v1, v2, v3}
{{0.308624, 0.0113816, "-XXX-", 0.100156}, 
 {0.368705, 0.44588, "-XXX-", 0.736246}, 
 {0.71764, 0.18652, "-XXX-", 0.338795}}

Yet another idea would be to use the compound object allv (see above),
and then

In[11]:= allv[[All, 2]] = "-YYY-"
Out[11]= "-YYY-"

In[14]:= allv
{{0.308624, "-YYY-", 0.452114, 0.100156}, 
 {0.368705, "-YYY-", 0.878839, 0.736246}, 
 {0.71764, "-YYY-", 0.667573, 0.338795}}

Of course the values of v1,... are not affected, but perhaps you may
dispense with them alltogether, or use them only for access or display

In[15]:= Clear[v1, v2, v3]
v1 := allv[[1]]; v2 := allv[[2]]; v3 := allv[[3]]

In[17]:= {v1, v2, v3}
{{0.308624, "-YYY-", 0.452114, 0.100156}, 
 {0.368705, "-YYY-", 0.878839, 0.736246}, 
 {0.71764, "-YYY-", 0.667573, 0.338795}}

Gruss, Hartmut

  • Prev by Date: Re: Re: PlotVectorField
  • Next by Date: Re: NDSolve series of ode with equilibrium conditions
  • Previous by thread: Set in Scan
  • Next by thread: Re: Set in Scan