[Date Index]
[Thread Index]
[Author Index]
Re: Changing names of variables in a loop
*To*: mathgroup at smc.vnet.net
*Subject*: [mg92218] Re: Changing names of variables in a loop
*From*: Albert Retey <awnl at gmx-topmail.de>
*Date*: Tue, 23 Sep 2008 07:33:07 -0400 (EDT)
*References*: <gb7obt$ngj$1@smc.vnet.net>
kazik.lakomy at gmail.com wrote:
> Hi,
> do you know maybe is there a possibility to change a name of a
> variable in a loop? I'm not exactly sure how to explain it, so maybe
> instead of my words I paste a basic example that express my query:
>
> a1 = 1; a2 = 2; a3 = 3;
> func[g_] := g;
> Summ = 0;
>
> For[i = 1, i <= 3, i += 1,
> Summa += func[ai]]
>
> So something like this... I have tried to deal with this like with
> strings and have put func[a<>"i"] but it didn't work (quite logic).
> The general problem is much more complicated, this is only a part of
> it, so please do not suggest me how can I sum up three numbers, this I
> believe I know :) I would very appreciate any hints,
this does literally what you want:
For[i = 1, i <= 3, i += 1,
summ += func[ToExpression["a" <> ToString[i]]]]
there are alternatives which save you from error prone typing of
irrelevant code:
summ = 0;
Do[summ += func[ToExpression["a" <> ToString[i]]], {i, 3}]
or:
summ = Total[Table[func[ToExpression["a" <> ToString[i]]], {i, 3}]]
if possible I would suggest to use different naming conventions for your
variables if you need to generate them programmatically:
a[1] = 1; a[2] = 2; a[3] = 3;
which lets you reduce your code to:
summ = 0;
Do[summ += func[a[i]], {i, 3}]
summ
or even:
summ=Total[Table[func[a[i]], {i, 3}]]
or:
Total[func /@ a /@ Range[3]]
hth,
albert
Prev by Date:
**Re: Using Mathematica with GSL**
Next by Date:
**Re: How to collect terms based the total power of x and y in (x +**
Previous by thread:
**Re: Changing names of variables in a loop**
Next by thread:
**labeling axes in a ContourPlot**
| |