Detach anonymous function from file in which it's defined

Viewed 75

I am looking for a workaround for the following problem:

  • Create a script foo.m containing fun = @(x)(x*x)
  • Run foo. This creates the variable fun.
  • Delete foo.m
  • Try running fun(2).

In recent versions of MATLAB (I am using R2019b) this results in an error:

Previously accessible file "foo.m" is now inaccessible.

Somehow, the anonymous function is tied to the file in which it was defined.

Is it possible to somehow "detach" it so that it would continue working even after the file was deleted?


For those curious why I need this, it is for fixing MATLink, the Mathematica/MATLAB interface, for recent versions of MATLAB.

1 Answers

You can use func2str and str2func to construct a new function handle that will work:

more_fun = str2func(func2str(fun));
more_fun(2)

Note that after this, fun can still not be found, but you can also assign to fun directly to make it accessible again.

Edit: just found a (documented) limitation: if the anonymous function uses outside variables, this method will not work, because

Function handles created using str2func do not have access to variables outside of their local workspace or to nested functions. If your function handle contains these variables or functions, MATLABĀ® throws an error when you invoke the handle.

Related