# Saving data in flat files using Mathematica

I am trying to solve a system $dx/dt =f (x, t)$ using the RK4 in Fortran 90 that works for any 2D Hamiltonian systems. I would like to generate using Mathematica a Fortran file .f90 that contains the terms (in FORTRAN SYNTAX) of the function $f(x, t)$ that corresponds to the right hand side of the RK4 solver. In the code it corresponds to the term deriv.

ndof = 2; ndim = 2*ndof;
Clear[h];
h = (1/2) (x^2 + x^2) + aa*x^2/2 - bb*Sqrt[x^2]^3/3 +
aa*x^2/2 - bb*Sqrt[x^2]^3/3 + aa*(x - x)^2/2 -
bb*Sqrt[(x - x)^2]^3/3;
derivq = Table[D[ h, x[i + ndof]]   , {i, 1, ndof}]
derivp = Table[-D[h, x[i]] , {i, 1, ndof}]
deriv  = Join[derivq, derivp]
filename = "1d_graphene_rk.f90"
$Output = filename; SetOptions[$Output]
Do[Print["dxdt(" <> ToString[i] <> ")=" <>
ToString[FortranForm[FullSimplify[deriv[[i]]]]]];, {i, 1, ndim}]
$Output = OutputStream["stdout", 1]; SetOptions[$Output]


it produces the following errors when trying to save deriv

Print::noopen: Cannot open 1d_graphene_rk.f90.
Print::noopen: Cannot open 1d_graphene_rk.f90.
Print::noopen: Cannot open 1d_graphene_rk.f90.
General::stop: Further output of Print::noopen will be suppressed
during this calculation.


How can I fix this code for it to work?

• Try $Output = OpenWrite["1d_graphene_rk.f90"]; – Pillsy Apr 24 '18 at 12:07 ## 1 Answer Export["test.f90", Table["dxdt(" <> ToString[i] <> ")=" <> ToString[FortranForm[FullSimplify[deriv[[i]]]]], {i, ndim}], "Text"] FilePrint["test.f90"] aside you may want to add Assumptions -> Element[{x, x}, Reals] to Simplify ( that will turn Sqrt[x^2] to Abs[x] ) note if you really want to do "low level" file i/o you should work with Write , WriteString etc instead of messing with Print / $Output

• Running the command as it is on the post, I am getting the following error OpenWrite::noopen: Cannot open /test.f90. '\$Failed. What is happening on my notebook :-( :-( ? – many Apr 25 '18 at 15:32
• oh you may be running in a directory where you do not have write permission. Do use SetDirectory` to set to somplace you can write or give a full path name to the file. – george2079 Apr 26 '18 at 0:32
• Great, many thanks. It works fine now. – many Apr 26 '18 at 10:27