4

I'd like to generate definitions of variables using an algorithm.

For example:

i'd like to run a loop that does the following p=p1 p^2=p2 p^3=p3

so for p^i i'd like to define a variable pi (i is a number).

1
  • i think i found it ToExpression["p"<>ToString[i]] Oct 15, 2010 at 0:09

1 Answer 1

4
badListEmulation[varName_?StringQ, maxIndex_?IntegerQ] := 

      ToExpression /@ 
             Table[(varName <> # <> "=" <> varName <> "^" <> #) & [ToString@i], 
                   {i, maxIndex}
             ];

Usage

 badListEmulation["var", 10]

Result

 {var, var^2, var^3, var^4, var^5, var^6, var^7, var^8, var^9, var^10}

 ?var3
 var3=var^3 ... etc

NB:

Of course is MUCH better to use a list. Something like

aList = Table[p^i,{i,6}];

aList[[3]]
p^3

But I guess you already know it.

HTH!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.