Assume we have this For
loop:
For[i=1,i<10,i++, i^2]
.
How can we put the squared values i^2
into a list?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityAssume we have this For
loop:
For[i=1,i<10,i++, i^2]
.
How can we put the squared values i^2
into a list?
For
loops are very ugly in Mathematica and should be avoided whenever possible. @march's solutions are so much more elegant.
But if you're wedded to the idea of using a For
loop, here's a very ugly approach to your problem:
mylist = {};
For[i = 1, i < 10, i++, AppendTo[mylist, i^2]]
and then
mylist
For
, an even uglier approach but more efficient than using AppendTo
is flattening nested lists. mylist = {}; (For[i = 1, i < 10, i++, mylist = {mylist, i^2}]; mylist = mylist // Flatten;)
$\endgroup$
– Bob Hanlon
Sep 29 '17 at 19:45
Table[i^2, {i, 9}]
.Range[9]^2
. See this post.. $\endgroup$ – march Sep 29 '17 at 17:43