1
$\begingroup$

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}]]

And:

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

1 Answer 1

7
$\begingroup$

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]]}];
$\endgroup$
1
  • 2
    $\begingroup$ But you can only do this once. If you try to use the 2nd line a second time, it fails. $\endgroup$ Nov 15, 2015 at 2:09

Your Answer

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

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