How do I use something like 'inputname' to give back name of struct and fieldname supplied?
16 views (last 30 days)
Show older comments
Andrew Tchieu
on 25 Mar 2022
Commented: Steven Lord
on 10 Aug 2022
foo.bar = 1;
a = 1;
get_names(foo.bar, a)
function get_names(x, y)
duh = inputname(1);
fprintf('inputname = %s\n', duh);
Prints empty. Is there any way to get it to print back 'foo.bar'.
0 Comments
Accepted Answer
Steven Lord
on 25 Mar 2022
No. Even if it could, that could be misleading.
foo = struct('x', 1);
foo(2).x = 3;
fun1680729(foo.x, 4)
function fun1680729(varargin)
format compact % Reduce the number of blank lines in the display
fprintf("This function was called with %d inputs.\n", nargin)
celldisp(varargin)
end
The call to fun1680729 looks like there are only two arguments, but due to the expression foo.x generating a comma-separated list the function is actually called with three inputs: foo(1).x, foo(2).x and 4. So if inputname could return the expressions that generated an input rather than the input itself, what should this function return if you asked it for the "name" of its second input? While the code in this post does include the literal foo(2) I could have created the struct without it. So should inputname display something that's not physically present in the original code?
0 Comments
More Answers (1)
YK_Valid
on 10 Aug 2022
try this :
myvar = 1;
get_myvar_name = @(x) inputname(1);
get_myvar_name(myvar)
1 Comment
Steven Lord
on 10 Aug 2022
As the documentation page for the inputname function states, "Workspace variable name, returned as a character vector. If the input argument has no name, the inputname function returns an empty character array (''). For example, an input argument has no name if it is a number, an expression, or an indexing expression instead of a variable."
In your example, you're calling get_myvar_name with a workspace variable as input. In the original example the get_names function is being called with the expression foo.bar, and as stated above inputname will return ''.
See Also
Categories
Find more on Argument Definitions in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!