Export custom formatted expressions from Mathematica

試著忘記壹切 提交于 2019-12-03 07:15:29

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!