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

4 visualizzazioni (ultimi 30 giorni)
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 !!!

Risposta accettata

Walter Roberson
Walter Roberson il 23 Ott 2021
Modificato: Walter Roberson il 23 Ott 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

Più risposte (1)

Image Analyst
Image Analyst il 23 Ott 2021
Modificato: Image Analyst il 23 Ott 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 Commenti
Saang Bum Kim
Saang Bum Kim il 24 Ott 2021
Modificato: Saang Bum Kim il 24 Ott 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 il 24 Ott 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.

Accedi per commentare.

Categorie

Scopri di più su Historical Contests in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by