Prev: trading
Next: Experimental Data Analyst
From: Peter Breitfeld on 25 Jul 2010 02:00 miguelwon wrote: > Hello. > > I'm working with some expressions that are dependent of several > variables co1, co2, ... , con. I would like to know how can I assign > values iteratively to some of these variables. I tried: > > For[i=1,i<=100,i++, > Symbol["co"<>ToString[i]]=0; > ]; > > but it doesn't work. For each iteration it says coi is Protected. > Can someone help me? > > Thanks > The error occurs, because you tried to assign the value 0 to an Expression with Head Symbol. One way to make lists of symbols is to use Array like this: Array[co,5] gives {co[1], co[2], co[3], co[4], co[5]} If you like to name your variables co1, co2,... (bad idea) you could do the following CC=Array["cc"<>ToString[#]&,5] {"cc1", "cc2", "cc3", "cc4", "cc5"} These are not Symbols but Strings, which is bad. So I would not recommend this, because you can't easily assign values to the list, whereas in the first case it's easy: Do[co[i]=10+i,{i,10}] co/@Range[5] {11, 12, 13, 14, 15} -- _________________________________________________________________ Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de
From: Leonid Shifrin on 25 Jul 2010 02:01
This will work, regardless of whether the variables already had some values or not: Table[ToExpression["co" <> ToString[i], InputForm, Function[s, s = 0, HoldAll]], {i, 100}] I would recommend using indexed variables like co[1], co[2] etc instead of co1, co2, etc - then it is even much easier: In[10]:= Clear[co]; In[11]:= Do[co[i] = 0, {i, 100}] In[12]:= co /@ Range[10] Out[12]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} Indexed variables are generally easier to manipulate than Symbols, particularly when you have many of them and want to manipulate them programmatically. Regards, Leonid On Sat, Jul 24, 2010 at 1:07 PM, miguelwon <miguelwon(a)gmail.com> wrote: > Hello. > > I'm working with some expressions that are dependent of several > variables co1, co2, ... , con. I would like to know how can I assign > values iteratively to some of these variables. I tried: > > For[i=1,i<=100,i++, > Symbol["co"<>ToString[i]]=0; > ]; > > but it doesn't work. For each iteration it says coi is Protected. > Can someone help me? > > Thanks > > |