필터 지우기
필터 지우기

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 CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by