Is there a way to Identify the calling function within a function?
122 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Douglas Anderson
le 3 Jan 2022
Commenté : Douglas Anderson
le 3 Jan 2022
Hello!
I would like a generic function that "knows" which function called it (to set certain variables) without having to pass it through varargin or any other argument passed like myfunc(hidden_argument).
A client will get source code for the calling functions, but not for the generic function, which will operate differently for each calling function.
Thanks!
Doug
Réponse acceptée
Adam Danz
le 3 Jan 2022
Modifié(e) : Adam Danz
le 3 Jan 2022
dbstack returns a structure containing information about the file, function name, and line number of the function call stack. The second element of the structure is the caller.
The structure will be empty if dbstack is called from the command line or by running the section in debug mode, and will contain only 1 element in the structure array if the function is called directly.
Example of stack info
stack = dbstack('-completenames')
stack =
2×1 struct array with fields:
file
name
line
% read second element in the structure array
stack(2)
ans =
struct with fields:
file: 'C:\Users\me\Documents\Matlab\myFunc.m'
name: 'myFunc'
line: 1
Use Case
stack = dbstack('-completenames');
if numel(stack) >= 2
fprintf('Caller is %s line %d in file %s.\n', stack(2).name, stack(2).line, stack(2).file)
else
fprintf('No caller.\n')
end
Note that the line number can be negative when stepping past the end of the file in debug mode.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Debugging and Analysis dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!