Is it possible for a function to know the caller's name of an argument, perhaps through introspection?
My use case: a generic/specialized helper function that prints out the variable name and (formatted) value? E.g., I have a function that prints out the position and velocity of an object that I use while debugging. I'd like to print out the variable's name and its position and vel. Yes, I can pass in the variable name, but I would like to bypass one step. R2026a is fine--I know it has new introspection functionality.
Here is a sample function.
function prtPosVel( pos, vel )
if( nargin < 2 )
vel = pos(4:6);
pos = pos(1:3);
end % if state was passed in
% Get the name of the pos variable passed in.
varName = "pos"; % Get actual name
% print to screen
fprintf("%s: pos=[%.3f,%.3f,%.3f]; vel=[%.3f,%.3f,%.3f]\n", ...
varName, pos, vel);
end % function prtPosVel
Thanks!

 Réponse acceptée

Caitlin
Caitlin le 3 Août 2026

2 votes

It sounds like you're describing inputname?

1 commentaire

Uday
Uday le 3 Août 2026
Modifié(e) : Uday le 3 Août 2026
Thanks, learnt something new today! This will have to do. From the helpfile you referenced, it can't find the name for a bunch of cases. But, that maybe the best we can do. Anyway, I accept your answer with thanks.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Produits

Version

R2026a

Community Treasure Hunt

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

Start Hunting!

Translated by