# How can I make my output to be added to an existing list?

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}}

For[i = 1, i < 6, i++,
For[e = 1, e < 6, e++ 1,
Print[Mod[v[[i]] + v[[e]], 2]]
]]


I have been trying to make all the output from the loop to be added to another list using AppendTo, but it doesn't work.

How can I do this task?

-
Look up Append – Sektor Jan 4 '14 at 5:36
Your first problem is that your nested For-loops make no output, so there is nothing to append to any external list. – m_goldberg Jan 4 '14 at 5:59

## 2 Answers

I don't know the reason for your problem because you did not show the code you attempted to use. I shall guess that you tried to use both Print and AppendTo; that won't work because the output of Print is Null. Also, instead of using AppendTo which will be very slow on long lists (because the array must be reallocated for each operation), I recommend using Sow and Reap, or even better replacing the loops entirely with Table, then merging the results with v = Join[v, result].

Sow and Reap:

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}};

result =
Reap[
For[i = 1, i < 6, i++, For[e = 1, e < 6, e++ 1, Sow[Mod[v[[i]] + v[[e]], 2]]]]
][[2, 1]];

v = Join[v, result];

v


Table:

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}};

v = Join[v, Table[Mod[v[[i]] + v[[e]], 2], {i, 5}, {e, 5}] ~Flatten~ 1]


Even better is to use vectorized functions. For example create your combinations using Tuples and apply Mod to all vectors at once:

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}};

v = v ~Join~ Mod[Plus @@@ Tuples[v, 2], 2]


Equivalently, using Total instead of Plus and Apply at level one (short form @@@):

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}};

v = Join[v, v ~Tuples~ 2 ~Total~ {2} ~Mod~ 2]


In case you are wondering, a ~f1~ b ~f2~ c is another way to write f2[f1[a, b], c].

-

This is a nice place to consider using Outer which calculates the outer product of a vector. Replacing the "product" with sum (Plus) gives the sum of all the terms. The Mod function can then be mapped to all the elements of the sum:

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}};
Mod[#, 2] & /@ Flatten[Outer[Plus, v, v, 1], 1]


which gives the desired output

{{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}, {1, 0, 0}, {0, 0, 0},
{0, 0, 1}, {1, 1, 1}, {0, 1, 1}, {1, 0, 1}, {0, 0, 1}, {0, 0, 0}, {1, 1, 0},
{0, 1, 0}, {0, 1, 1}, {1, 1, 1}, {1, 1, 0}, {0, 0, 0}, {1, 0, 0}, {1, 1, 1},
{0, 1, 1}, {0, 1, 0}, {1, 0, 0}, {0, 0, 0}}


As Simon suggests, the somewhat simpler form:

Mod[Flatten[Outer[Plus, v, v, 1], 1], 2]


also does the job.

-
+1 but note that Mod is Listable so there's no need to map it: Outer[Plus, v, v, 1] ~Flatten~ 1 ~Mod~ 2 – Simon Woods Jan 4 '14 at 12:16