Reputation: 5054
I have a function f[a]
. I run it through Table
to generate a huge list of values for later use in a C program as a lookup table. I want to export this to CSV so I can copy/paste it into my code editor and quickly turn it into a C array (all I'd have to do is wrap it in curly braces and give it a name):
Export["myfile.csv", Table[ f[a], {a, 0, 6} ], "CSV" ];
What I want is this:
0, 1, 2, 3, 4, 5, 6
and so on, but I end up with this:
0
1
2
3
4
5
6
Each entry is on a new line. What simple, obvious thing have I missed?
Thanks!
Upvotes: 6
Views: 3824
Reputation: 14731
You could export using the more general "Table" format and specify the line separators. For example:
Export["myfile.csv", Table[f[a], {a, 0, 6}], "Table", "LineSeparators" -> ", "]
FilePrint["myfile.csv"]
(* Returns:
f[0], f[1], f[2], f[3], f[4], f[5], f[6]
*)
You might also need to specify the "FieldSeparators"
option, it's default for the "Table"
format is "\t"
.
Upvotes: 12
Reputation: 24336
If your export object is a single list, you can avoid modifying its elements, and just wrap it in List
:
Export["myfile.csv", List @ Table[f[a], {a, 0, 6}]]
Upvotes: 6
Reputation: 16232
How about using Partition
?
f[x_] = Sin[x/10.];
Export["C:\\Users\\Sjoerd\\Desktop\\myfile.csv",
Partition[Table[f[a], {a, 0, 600}], 30],
"CSV"
];
Upvotes: 3
Reputation: 42225
This should do what you want:
Export["myfile.csv", Transpose@Table[{f@a}, {a, 0, 6}], "CSV"]
Your approach will result in a column vector, which leads to each row being written out on a new line. Creating the table as a row vector solves this problem. In this case, each column is separated by a comma.
Creating a list of lists seems a klunky way to do it, but that's how Mathematica treats it internally anyway. If you import the CSV file from your code in the question:
Import["myfile.csv"]
Out[1]={{0}, {1}, {2}, {3}, {4}, {5}, {6}}
you see that Mathematica has automatically stuffed each element into a list. So it will have to be stuffed in a list, either this way or as in Mr.Wizard's answer.
Upvotes: 4