Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write MATLAB functions in Jupyter Notebook?

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
like image 596
splinter Avatar asked Feb 06 '18 23:02

splinter


People also ask

Can you do MATLAB in Jupyter notebook?

You can integrate MATLAB with an existing JupyterHub deployment, single user Jupyter Notebook Server, and many other Jupyter-based provisioning systems running in the cloud or on-premises. You can open MATLAB from the Jupyter interface to directly work in MATLAB without leaving your web browser.

Is there a notebook for MATLAB?

Description. notebook starts Microsoft® Word software and creates a new MATLAB® Notebook titled Document 1 . The notebook command is available only on Windows® systems that have a 32–bit version of Microsoft Word installed. The notebook command is not available for 64–bit versions of Microsoft Word.


1 Answers

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.

like image 80
Guillaume Avatar answered Oct 01 '22 19:10

Guillaume