teozturk
(Teoman Ozturk)
October 20, 2013, 1:26pm
1
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]
Close[a1]
It doesn’t work. Can you help me please? Thanks.
Teoman
cormullion
(C ormullion)
October 20, 2013, 3:19pm
2
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}]
Close[a1];
teozturk
(Teoman Ozturk)
October 21, 2013, 3:33pm
3
thank yo very much dear C ormullion. But is it possible write the results on the screen and to a file?
cormullion
(C ormullion)
October 21, 2013, 6:24pm
4
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];
Close[a1]
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.
teozturk
(Teoman Ozturk)
October 21, 2013, 7:36pm
5
thank you very much, you are great! it works.