How do I use something like 'inputname' to give back name of struct and fieldname supplied?
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Andrew Tchieu
el 25 de Mzo. de 2022
Comentada: Steven Lord
el 10 de Ag. de 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 comentarios
Respuesta aceptada
Steven Lord
el 25 de Mzo. de 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 comentarios
Más respuestas (1)
YK_Valid
el 10 de Ag. de 2022
try this :
myvar = 1;
get_myvar_name = @(x) inputname(1);
get_myvar_name(myvar)
1 comentario
Steven Lord
el 10 de Ag. de 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 ''.
Ver también
Categorías
Más información sobre Argument Definitions en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!