14
votes

Overview

I am using the MATLAB kernel in Jupyter Notebook. I would like to write a function in the notebook, rather than referring to a function that is saved in another .m file. The problem is that when I try to do so, I get the error:

Error: Function definitions are not permitted in this context.

Visual example:

In a new notebook, it looks like the following picture:

enter image description here

Now, it does work if I make a new .m file:

enter image description here

and then call then function via the notebook:

enter image description here

but this is inconvenient. Is there a way to define functions from within a Jupyter Notebook directly?

My software

  • MATLAB 2017b
  • Windows 10
  • Jupyter running in chrome
  • Jupyter installed via anaconda
1
This looks like a limitation of the MATLAB kernel. If you look at the kernel source, you can see that they're using eval, which doesn't accept function definitions. For example, if you try eval('function trialcode() asdf = 1; end') in MATLAB you'll receive the same error.excaza
Evil eval has done it again!buzjwa
@buzjwa As Mermaid Man would say, EEEEVAAAAAALLLLL!!!Mateen Ulhaq

1 Answers

15
votes

The documentation indicates that you can use the magic:

%%file name_of_your_function.m

To take your example, your cell should be written as follows:

%%file fun.m

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

This creates a new file called fun.m. This allows MATLAB to do what it needs (a function in a separate file), and also allows you to write your function directly in the Jupyter Notebook.