I'm new to Mathematica and I'm struggling to adapt to what I "believe" would be a more Mathematica-esque approach to things from my procedural programming background. Specifically I am struggle to create lists in a clean way that require more than one line to create the expression whose outputs will be the entries.

To try and illustrate, let's suppose we want to create a list of random points in the unit circle and that we'll do this by choosing random points in polar coordinates and then convert them to cartesian coordinates. I feel like the Table function is the cleanest way to make a list in Mathematica, but unless I make an additional function it doesn't seem like there is a good way to go about this. To reiterate, I'd like an approach that uses something like Table but does not require creating a function

To illustrate consider the following code

 r := RandomReal[{0, 1}];
theta := RandomReal[{0, 2*Pi}];
Pts = Table[{r*Cos[theta], r*Sin[theta]}, {i, 1, 100}];

This fails to generate random points in the unit circle because r and theta appear twice and thus are not the same within each generated point.

The only work around, still using Table, I can think of involves creating a function but again, I want to avoid this. For example I want to avoid this workaround:

GetPt[r_, theta_] := {r*Cos[theta], r*Sin[theta]};
Pts = Table[
   GetPt[RandomReal[{0, 1}], RandomReal[{0, 2*Pi}]], {i, 1, 100}];

Admittedly, I think this is a perfectly fine approach, but in the interest of learning flexibility I'm trying to get a sense of all the possible ways to do something.

A for loop will get around this but generating a list with Append does not seem very clean. e.g.

Pts = {};
For[i = 0, i < 100, i++,
 r = RandomReal[{0, 1}];
 theta = RandomReal[{0, 2*Pi}]; 
 AppendTo[Pts, {r*Cos[theta], r*Sin[theta]}]

Hopefully it makes sense what my question is. Anny suggestions or comments are welcome. Thank you for your time.


1 Answer 1


To invoke r and theta once in every step you can do

Pts1 = Table[{(r1 = r)*Cos[t = theta], r1 Sin[t]}, {i, 1, 100}];


Pts2 = Table[With[{r1 = r, t = theta}, r1 {Cos[t], Sin[t]}], {i, 1, 100}];

Both approaches give the same result when used with same seed:

Pts1 == Pts2


To get a list with similar structure directly you can use:

rlist = RandomReal[{0, 1}, 100];
tlist = RandomReal[{0, 2 Pi}, 100];
Pts3 = rlist Transpose[{Cos[tlist], Sin[tlist]}]

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.