jupyter-matlab-proxy icon indicating copy to clipboard operation
jupyter-matlab-proxy copied to clipboard

Local functions defined in cells persist across cells.

Open rsp34 opened this issue 1 year ago • 4 comments

Really like "With MATLAB R2022b and later, you can define a local function at the end of the cell where you want to call it".

Would be great if the functions could be called in other cells without re-writing the local function.

rsp34 avatar Sep 11 '23 16:09 rsp34

Thank you for the feature request @rsp34 ! Our teams will consider this for a future release of the product.

From the outset, there may be challenges to implement this in a way that disambiguates functions with local cell scope from functions that have notebook scope.

Nonetheless a worthwhile feature request!

prabhakk-mw avatar Sep 12 '23 04:09 prabhakk-mw

Also requested by @christianschroder here.

In-lining his thoughts below:

BTW, one remark: it would be nice if, for larger notebooks, it were possible to declare functions in the standard manner (function out = myfun(in) ... end) in cells of their own, and have them be available for all cells subsequently executed. Right now, as far as I can tell a function declared this way is only callable within the cell, so

myfun(3, 4)
function c = myfun(a, b)
    c = a^2 + b^2;
end

will work and output 25, but writing

function c = myfun(a, b)
    c = a^2 + b^2;
end

and then

myfun(3, 4)

in subsequent cells will not, instead giving you an error (Unrecognized function or variable 'myfun'.) Anonymous functions and function handles work, of course - but I'm sure you can see why supporting proper, named functions would be useful, so I'd like to suggest this for the future.

prabhakk-mw avatar Nov 02 '23 08:11 prabhakk-mw

Yes, this would be very helpful. One way that I used python notebooks in grad school was to define a main function in a high-up cell that would analyze results for a scenario of parameter values, then plot the results in various ways. In the subsequent cells you could just create a scenario then call that analysis and plotting function.

In Matlab notebooks, you can of course define a function in its own .m file and put that on the path, but then you lose access/ability to read that function code right as part of the notebook.

tylerlekang avatar Dec 21 '23 19:12 tylerlekang

Hello @rsp34,

As of version v0.14.0, the MATLAB Kernel now supports Magic commands, enabling you to use %%lsmagic, %%help, %%time, and %%file magics with the Kernel. The %%file magic can be used as a workaround for your issue by defining local functions within a cell and saving that function into a file, enabling you to use that function throughout the notebook. You can find a brief guide on this in the Magics README.

Kindly let me know if this approach worked or proved useful in solving the issue you are facing.

Thank you for using MATLAB Integration for Jupyter!

Shushant2502 avatar Aug 30 '24 06:08 Shushant2502