如何在Jupyter Notebook中编写MATLAB函数?

How to write MATLAB functions in Jupyter Notebook?

总览

我在Jupyter Notebook中使用MATLAB内核。 我想在笔记本中编写一个函数,而不是引用保存在另一个.m文件中的函数。 问题是当我尝试这样做时,出现错误:

Error: Function definitions are not permitted in this context.

视觉示例:

在一个新的笔记本中,如下图所示:

enter image description here

现在,如果我创建一个新的.m文件,它确实可以工作:

enter image description here

然后通过笔记本调用then函数:

enter image description here

但这很不方便。 有没有一种方法可以直接从Jupyter Notebook内部定义功能?

我的软件

  • MATLAB 2017b
  • Windows 10
  • 在Chrome中运行的Jupyter
  • 通过Python安装的Jupyter


文档表明您可以使用魔术:

1
%%file name_of_your_function.m

以您的示例为例,您的单元格应编写如下:

1
2
3
4
5
%%file fun.m

function out = fun(in)
    out = in + 1;
end

这将创建一个名为fun.m的新文件。 这使MATLAB可以执行所需的工作(在单独文件中的函数),还允许您直接在Jupyter Notebook中编写函数。