Message Boards Message Boards

4 Replies
3 Total Likes
View groups...
Share this post:

writing data to a file from loop

Posted 11 years ago
Hello Everyone,
I have just started to learn Mathematica. I am trying to writing data to a file from loop like this:
calc1 := For[i = 1, i < 6, i++, Print[Integrate[i*x^2, {x, 0, 1}]]]
a1 = OpenWrite["calc.dat", FormatType -> OutputForm]
Write[a1, calc1]

It doesn't work. Can you help me please? Thanks.

POSTED BY: Teoman Ozturk
4 Replies
Posted 11 years ago
thank yo very much dear C ormullion.  But is it possible write the results on the screen and to a file?
POSTED BY: Teoman Ozturk
This is one possibility: use a function to print each value and write each value one element at a time:
a1 = OpenWrite["calc2.dat", FormatType -> OutputForm];
data = Table[OutputForm@Integrate[i*x^2, {x, 0, 1}], {i, 1, 6}];
Map[(Print[#]; Write[a1, #]) &, data];
There are many ways to do this type of thing. But for large lists it might be better to write everything in one fell swoop, rather than item by item. 
POSTED BY: C ormullion
Posted 11 years ago
thank you very much, you are great! it  works.
POSTED BY: Teoman Ozturk
Print doesn't return a value,  just prints things as a side effect. So although you see the values in the notebook, they aren't returned by the call to calc1. 

I would try something like this:
a1 = OpenWrite["calc.dat", FormatType -> OutputForm];
Table[Write[a1, Integrate[i*x^2, {x, 0, 1}]], {i, 1, 6}]
POSTED BY: C ormullion
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract