3
votes

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
@CrisLuengo That was just a typo (fixed now). I am calling fun. It doesn't work if foo.m was deleted, even though MATLAB knows about the fun variable, and can even show me the definition.Szabolcs
Does defining fun as a global variable,both in the command line and in the script, work?rahnema1
@rahnema1 No. But aren't they global by default anyway?Szabolcs
No. I mean if you use the global keyword to declare variables.rahnema1
@rahnema1 I understand what you wanted to try. It does not change anything. Does it work for you?Szabolcs

1 Answers

3
votes

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.