How can we know whether the current execution of command is conducting inside a function or not?

4 views (last 30 days)
How can we know whether the current execution of command is conducting inside a function or not?
When I develop a function, I frequently check some parts of the code for the function in base command envirenment.
I wonder is there any method to identify whether the current execution is conducting inside of a function or
it is conducting in the base environment.
Thanks in advance !!!

Accepted Answer

Walter Roberson
Walter Roberson on 23 Oct 2021
Edited: Walter Roberson on 23 Oct 2021
The functions nargin and nargout will error if executed at the base. So you can use try/catch
inbase = false; try; nargin; catch ME; inbase = true; end

More Answers (1)

Image Analyst
Image Analyst on 23 Oct 2021
Edited: Image Analyst on 23 Oct 2021
You can call fprintf immediately upon entering and just befor leaving the function:
fprintf('Entering MyFunction().\n');
fprintf('Leaving MyFunction().\n');
If you stop at a break point, you can check the call stack on the tool bar. Or you can get the call stack from my attached function and print it out inside the function.
  5 Comments
Saang Bum Kim
Saang Bum Kim on 24 Oct 2021
Edited: Saang Bum Kim on 24 Oct 2021
As I understand the attached file, GetCallStack.m, runs like,
try
% Some code that might throw an error......
catch ME
callStackString = GetCallStack(ME);
end
I think that the dbstack() what @Stephen suggested could similar works more easily.
I fount that the modified method from what @Stephen suggested works well until now:
~(length({output(@() dbstack,1).name})-2)
Image Analyst
Image Analyst on 24 Oct 2021
@Saang Bum Kim, okay. I don't see Stephen on this thread, but it looks like you've accepted the Answer from Walter so I guess everything is figured out and working now. Best wishes.

Sign in to comment.

Categories

Find more on Historical Contests in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!