I want to compute a multidimensional table in Mathematica and write it to an external file. Here is a simple example. I have three lists x
, y
, z
and the output include all possible combinations of sums.
In the output file, I want 27 = 3x3x3 rows. Each row should have four values: x
, y
, z
and x+y+z
. Here is my code.
x = {1, 2, 3};
y = {4, 5, 6};
z = {7, 8, 9};
output = Table[x[[i]] + y[[j]] + z[[k]], {i, 1, 3}, {j, 1, 3}, {k, 1, 3}]
sfile = OpenWrite["C:\\Temp\\test.txt"]
For[i = 1, i <= 3, i++,
{For[j = 1, j <= 3, j++,
{For[k = 1, k <= 3, k++,
Write[sfile, x[[i]], y[[j]], z[[k]], output[[i, j, k]]]]}]}]
Close[sfile]
The problem is there is no space in the output file. So I get something like
14712
14813
14914
15713
15814
but I actually want
1 4 7 12
1 4 8 13
1 4 9 14
1 5 7 13
1 5 8 14
I need help to get the format above. I am quite new to Mathematica and don't know much about other functions. I am OK with any functions as long as they can generate the output I want. Thank you.
Export
? Do you need sequential file operations? $\endgroup$Write
. Mathematica does not put a space between expressions. $\endgroup$