2
$\begingroup$

I want to create a number of variables and assign random values to them. This is possible in Python using a single line of command.

To be more specific say I want to create 10 variables whose value will be $[0.1,1]$ randomly. Instead of declaring every variable individually and then assigning values to them, is there any easier way to do this in Mathematica?

$\endgroup$

closed as off-topic by Jens, MarcoB, LLlAMnYP, dr.blochwave, ilian Aug 21 '15 at 3:57

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Jens, MarcoB, LLlAMnYP, dr.blochwave, ilian
If this question can be reworded to fit the rules in the help center, please edit the question.

4
$\begingroup$

Edit

Here is a Mathematica one-liner, courtesy of ciao, that does what you ask for:

SeedRandom[42];
Array[(x[#] = RandomReal[1]) &, 10];

Definition @ x
x[1] = 0.425905
x[2] = 0.391023
x[3] = 0.347069
x[4] = 0.453741
x[5] = 0.555963
x[6] = 0.289169
x[7] = 0.296848
x[8] = 0.206408
x[9] = 0.32517
x[10] = 0.973325

And here is another one, producing non-indexed variables.

SeedRandom[42];
MapThread[Set, {Symbol["x" <> #] & /@ IntegerString[Range[10]], RandomReal[1, 10]}];

List @@ OwnValues /@ Hold[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10]
{{HoldPattern[x1] :> 0.425905}, {HoldPattern[x2] :> 0.391023}, 
 {HoldPattern[x3] :> 0.347069}, {HoldPattern[x4] :> 0.453741}, 
 {HoldPattern[x5] :> 0.555963}, {HoldPattern[x6] :> 0.289169}, 
 {HoldPattern[x7] :> 0.296848}, {HoldPattern[x8] :> 0.206408}, 
 {HoldPattern[x9] :> 0.32517}, {HoldPattern[x10] :> 0.973325}}
$\endgroup$
  • $\begingroup$ Why not just Array[(x[#] = RandomReal[1]) &, 10] for the first? $\endgroup$ – ciao Aug 21 '15 at 0:32
  • 1
    $\begingroup$ @ciao. Because I didn't think of that. $\endgroup$ – m_goldberg Aug 21 '15 at 0:35
  • $\begingroup$ @m_goldberg, thanks for such elaborated answer. $\endgroup$ – jhon_wick Aug 21 '15 at 2:15

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