In matlab one can use dbstack to retrieve the call stack at the current time, however dbstack is not available in standalone compiled versions of matlab programs, is there an alternative to get the call stack, or at least the function calling the current function? I want to write a facility function that needs to know by who it was called, but a full call stack would be preferable.
Here's where the solutions stand so far:
- As you mentioned, the function DBSTACK is on the list of functions that are not supported by the MATLAB Compiler, so it can't be used.
- You also mentioned in a comment that even though the function EVALIN isn't on the unsupported function list your compiler still won't allow you to use it. That ended up rejecting some of the previous solutions I suggested.
- Having to maintain your own stack trace by passing arguments along the chain of function calls (or possibly by storing them in a global variable) is not an ideal option due to the complexity and extra work it would take to maintain.
However, I have one more possible solution that I think is the "cleanest" one yet: using the error handling mechanisms to get at the stack trace. This will vary based on the MATLAB version you are using...
MATLAB Versions 7.5 (R2007b) and newer:
New error-handling capabilities in the form of the MException class were introduced in Version 7.5. You can get information about the stack trace from MException objects by creating and throwing a "dummy" exception, then immediately catching it and accessing the stack
field. If you do the following in a function:
try
throw(MException('phony:error',''));
catch ME
callerStack = {ME.stack.name};
end
Then the cell array callerStack
will contain the names of all the functions in the call stack, with the current function name in the first element and the top-most caller name in the last element.
MATLAB Versions 7.1 (R14SP3) through 7.4 (R2007a):
For these earlier versions you can use the ERROR function to throw an error and the LASTERROR function to capture the error and get the stack information:
try
error('phony:error','');
catch
s = lasterror;
callerStack = {s.stack.name};
end
MATLAB Versions 7.0.4 (R14SP2) and earlier:
Unfortunately, the LASTERROR function only started returning stack trace information in MATLAB Version 7.1, so there is no version of the above solutions that I can come up with for earlier MATLAB versions.