Azzera filtri
Azzera filtri

How do I use something like 'inputname' to give back name of struct and fieldname supplied?

10 visualizzazioni (ultimi 30 giorni)
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'.

Risposta accettata

Steven Lord
Steven Lord il 25 Mar 2022
No. Even if it could, that could be misleading.
foo = struct('x', 1);
foo(2).x = 3;
fun1680729(foo.x, 4)
This function was called with 3 inputs. varargin{1} = 1 varargin{2} = 3 varargin{3} = 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?

Più risposte (1)

YK_Valid
YK_Valid il 10 Ago 2022
try this :
myvar = 1;
get_myvar_name = @(x) inputname(1);
get_myvar_name(myvar)
  1 Commento
Steven Lord
Steven Lord il 10 Ago 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 ''.

Accedi per commentare.

Categorie

Scopri di più su Argument Definitions in Help Center e File Exchange

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by