I'm trying to do the following:

R = {a, b, c, d, e, f, g, h, i};
Table[R[[n]] = RandomInteger[{0, 20}], {n, 1, Length[R]}]

My intention is to assign a random value to each of these variables. But somehow it's not working. What else do I need to do? I've tried to do:

ToExpression[R[[n]] = RandomInteger[{0, 30}]]


Evaluate[R[[n]] = RandomInteger[{0, 30}]]
  • 3
    $\begingroup$ Hello Gustavo, you'll want to avoid assigning things to capital letters. That being said, try Scan[(# = RandomInteger[{0, 30}]) &, R]. $\endgroup$ – J. M.'s ennui May 24 '15 at 22:45

Remember that = is really Set, and Set is a pretty ordinary function. Also, RandomInteger can make a list all by itself, so you don't need Table.

Edit 11/15: Jerry Guern pointed out the need to be careful with quoting to have it work repeatedly. Here, I use Unevaluated to quote each variable:

r = Unevaluated /@ {a, b, c, d, e, f, g, h, i};

Now, you may use r repeatedly as input to:

MapThread[Set, {r, RandomInteger[{0, 20}, Length[r]]}];
  • 2
    $\begingroup$ But you can only do this once. If you try to use the 2nd line a second time, it fails. $\endgroup$ – Jerry Guern Nov 15 '15 at 2:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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