Export custom formatted expressions from Mathematica

前端 未结 1 820
有刺的猬
有刺的猬 2021-02-09 08:41

How can I get Mathematica to export/save/write a text file with proper Fortan77 formatting, that is, 72 columns and a continuation marker on the sixth column?

I am using

相关标签:
1条回答
  • 2021-02-09 09:09

    This is a job for the surprisingly little-known Splice function. First, you make a template file, with the extension ".mf", like so:

    file = "test.mf";
    
    out = OpenWrite[file];
    
    WriteString[out, "MH1 = <* form *>"];
    
    Close[out];
    

    Now when you use Splice, Mathematica will automatically replace everything between the <* and *> delimiters with its evaluated form. So if you set

    form = 4 + b9^2 + c1^5 + c4^5 + h10^4 + j2 + k10^4 + p10^4 + q5^5 + 
           q8 + s3^3 + s7^2 + t6^3 + u3^2 + u9^3 + x8^4 + z2^3;
    

    and call

    Splice["test.mf", PageWidth -> 72];
    

    which will automatically infer you want FortranForm output from the file extension, and which allows you to set PageWidth as an option, you will get a pretty decent result in the automatically generated file "test.f" (note the new extension):

    MH1 =         4 + b9**2 + c1**5 + c4**5 + h10**4 + j2 + k10**4 + p10**4 + 
        -  q5**5 + q8 + s3**3 + s7**2 + t6**3 + u3**2 + u9**3 + x8**4 + 
        -  z2**3
    

    Look at the docs for Splice for more options (changing the name of the output file and the like).

    0 讨论(0)
提交回复
热议问题