如何在Mathematica中编写一个长函数? 使用Notebook作为功能?
我在Mathematica笔记本的开头定义了一些变量,然后用它来计算我的结果。 现在,我想对变量的不同值进行几次相同的计算,并在某处使用结果。 所以用这个变量作为参数定义一个新的函数并且将笔记本的内容定义为body将会很有用。 但是之后我必须将所有内容写入单一输入行,并且没有办法看到中间结果。
有没有什么好办法来处理这种情况?
为了澄清我的意思,一个简短的例子:
我能做的就是这样的:
In[1] := f[variable_] := (
calculations;
many lines of calcalutions;
many lines of calcalutions;
(* some comments *);
(* finally the result... *);
result
)
然后使用这个功能:
In[1] := f[value1] + f[value2]
但是如果有人对函数f(“计算”)的第1行的中间结果感兴趣,那么就需要将行复制到其他地方。 但是,您不能只删除行尾的分号来查看行的结果。
运用
lc = Notebook[{Cell[
BoxData[((Pause[1]) ;)]
, "Input"], Cell[
BoxData[((Print[(Date[])]) ;)]
, "Input"], Cell[
BoxData[((Print[
("variable = ", variable)] ) ;)]
, "Input"], Cell[
BoxData[(result = (variable^2))]
, "Input"]}, WindowSize ->
{701, 810}, WindowMargins ->
{{Automatic, 149}, {Automatic,
35}}, FrontEndVersion -> "8.0 for Microsoft Windows (64-bit) (October
6, 2011)", StyleDefinitions ->
"Default.nb"];
或者,如果您将其保存在longcalc.nb中,则与工作笔记本相同的目录中
lc = Get[FileNameJoin[{SetDirectory[NotebookDirectory[]], "longcalc.nb"}]];
现在,在你的工作笔记本评估:
f[var_] := (variable = var;
NotebookEvaluate[NotebookPut[lc], InsertResults -> True]);
f[value1] + f[value2]
会做你想做的。
如果你这样做
f[variable_] := (
{calculations,
many lines of calcalutions,
many lines of calcalutions,
(* some comments *);
(* finally the result... *);
result}
)
那么你的函数将返回一个列表{ir1,ir2,...,result}
,其中ir1
等是中间结果。 然后{ir1,ir2,..,re}=f[value]
您可以分配{ir1,ir2,..,re}=f[value]
,其中re
将包含最终结果,而ir
则为中间结果。
这是否工作?
你也可以做intRes={};
外部函数和函数内部的转储值。 当然,如果在函数内部使用并行化,或者并行化整个函数,这会变得棘手。
AppendTo[intRes,ir1];
AppendTo[intRes,ir2];
要么
f[variable_] := Block[{output={}},
calculations;
AppendTo[output,ir1];
many lines of calcalutions;
(* some comments *);
AppendTo[output,ir2];
(* finally the result... *);
{output,result}];
并执行为{intRes,result}=f[var];
- intRes将是一个interrim结果列表。
如果您不需要保留中间结果进行计算,只需查看它们,那么有更多更好的方法来查看即将发生的事情。
对于较慢的功能,请使用Monitor[]
或Dynamic[]
或PrintTemporary[]
或ProgressIndicator[]
这些输出的结果随着功能的进展而改变和/或消失。
如果你想要一个更加永久的记录(假设函数真的运行得很快),那么使用Print []来查看中间输出。
除非你需要在计算中使用中间结果。
链接地址: http://www.djcxy.com/p/35589.html上一篇: How to write a long function in Mathematica? Using Notebook as function?