function - 如何在Mathematica中编写长函数?使用笔记本功能吗?

标签 function wolfram-mathematica

我在Mathematica笔记本的开头定义了一些变量,然后用它来计算结果。现在,我想对变量的不同值进行几次相同的计算,并在某处使用结果。因此,使用此变量作为参数定义我的笔记本的内容作为主体来定义一个新函数会很有用。但是然后,我将必须将所有内容都写在一个输入行中,并且没有舒适的方法来查看中间结果。

有什么好的方法来处理这种情况?

为了阐明我的意思,下面是一个简短的示例:

我能做的是这样的:

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]

会做你想要的。

关于function - 如何在Mathematica中编写长函数?使用笔记本功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377750/

相关文章:

linux - Bash 在后台运行函数

javascript - 从函数返回 boolean 值

c++ - 在 C 或 C++ 中返回结构是否安全?

matrix - 线性求解数学

functional-programming - Mathematica 相当于 Ruby 的 inject

matlab - 如何在 MATLAB 中将移动窗口应用于二维矩阵?

javascript - 删除并重新添加函数 javascript?

3d - 如何将 TetGen 用于这个简单的 3D 几何体

wolfram-mathematica - 您如何在Mathematica中访问ARGV?

wolfram-mathematica - 关于Internal`Bag的使用,有没有官方文档?