3

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
Community
  • 1
  • 1
Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
  • possible duplicate of [Access variable from other workspace in Matlab?](http://stackoverflow.com/questions/8572177/access-variable-from-other-workspace-in-matlab) – Eitan T Sep 12 '13 at 17:15
  • Related, and the title would suggest it, but after reading that question and answer (which is pretty much already included in this question) I don't think it is a duplicate. – Dennis Jaheruddin Sep 12 '13 at 19:09
  • IMO that's basically the same question, except having the `'base'` workspace instead of the `'caller'` workspace, as in your case. – Eitan T Sep 12 '13 at 19:20

1 Answers1

4

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.

Nick
  • 3,143
  • 20
  • 34
  • Thanks, can't believe I missed this. Do you think there is a way to get anything between the base and the caller? Or get a list of workspaces? – Dennis Jaheruddin Sep 12 '13 at 15:29
  • You can use `dbstack` to get a list of workspaces, however it is not possible to go access those with `evalin`. – Nick Sep 12 '13 at 15:32