|
|
Re: problem with append
Posted:
Jan 21, 2013 12:07 AM
|
|
Paolo,
Welcome to Mathematica!
You made two basic errors in your code:
(1) At each pass through the inner loop, rr gets reset to the empty list; you should initialize rr before the loop.
(2) The correct function name is AppendTo ("camel-case").
So you could correct your code to:
rr = {}; For[a = 2, a < 6, a++, For[b = 2, b < 6, b++, AppendTo[rr, a^b]]] rr
I suspect you came to Mathematica after using a procedural programming language where you had little choice but to spell out in detail such iterations. In Mathematica, however, there are _much_ easier ways to construct to kind of list you want.
Flatten[Outer[Power, Range[2, 5], Range[2, 5]]]
Explanation: Range[2, 5] gives {2, 3, 4, 5}. Outer applies its 1st argument, here Power, to each element of its 2nd argument ( Range[2, 5]) paired with each element of its 3rd argument (also Range[2, 5] ). The result of that is the nested list: {{4, 8, 16, 32}, {9, 27, 81, 243}, {16, 64, 256, 1024}, {25, 125, 625, 3125}} Flatten of that unseats that, giving just a plain 1-level list.
One might call the method with Outer a "functional" approach.
Another way that more directly exposes the iteration involved is by using Table:
Flatten[Table[a^b, {a, 2, 5}, {b, 2, 5}]]
WAlthough the numbers in your example are modest in size, and efficiency should not be at the top of your concerns as a Mathematica beginner, still it's illuminating to compare the efficiency of your original, explicitly iterative For loop as compared with the functional and Table approaches. For that, I changed the upper bound 5 to 1000.
rr = {}; Timing[For[a = 2, a < 1001, a++, For[b = 2, b < 1001, b++, AppendTo[rr, a^b]]];] (* on my 3.4 GHz Core i7 iMac with 16GB RAM, this was still running after 10 minutes! *)
Timing[Outer[Power, Range[2, 1000], Range[2, 1000]];] {3.368449, Null}
Timing[Flatten[Table[a^b, {a, 2, 1000}, {b, 2, 1000}]];] {3.527593, Null}
Slight advantage to the functional approach over Table. The For loop method is out of the question!
On Jan 20, 2013, at 1:21 AM, Paolo cachecho <paolocach@gmail.com> wrote:
> hello i am new to mathmatica.i have the following problem if anyone could help. > > For[a = 2, a < 6, a++, > For[b = 2, b < 6, b++, > Appendto[rr = {}, a^b]]] > rr > > but rr remains empty. how can i solve this > thank you
--- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2838 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305
|
|