フィルターのクリア

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

10 ビュー (過去 30 日間)
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'.

採用された回答

Steven Lord
Steven Lord 2022 年 3 月 25 日
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?

その他の回答 (1 件)

YK_Valid
YK_Valid 2022 年 8 月 10 日
try this :
myvar = 1;
get_myvar_name = @(x) inputname(1);
get_myvar_name(myvar)
  1 件のコメント
Steven Lord
Steven Lord 2022 年 8 月 10 日
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 ''.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by