Search code examples
matlabfunctionworkspace

Matlab navigate function workspace


I am looking for a way to access variables from other workspaces, in particular the workspace from which the current function is called.

I know how to do it in the simple case:

% Get a variable called `x` from the base workspace
x = evalin('base', 'x');

However, think of a situation where my function myFun, is called by many different functions (which I cannot edit). And I just know that each of them will have a variable x.

Now, how would I be able to see the variable x from the workspace in which myFun is called?

So I guess the key point in my question is:

How can I programmatically navigate to the above workspace?


Here is how it can be done manually:

  1. Set a breakpoint
  2. Once the breakpoint is hit use dbup
  3. Find x and look at it (or do something with it (with evalin or save/load for example)
  4. Hit f5

Solution

  • How about:

    x = evalin('caller', 'x')
    

    There is a limitation however, from Matlab's documentation:

    evalin cannot be used recursively to evaluate an expression. For example, a sequence of the form evalin('caller','evalin(''caller'', ''x'')') doesn't work.

    However, evalin is not a great function. Any usage should be avoided imho.