Passing both the the variable name and value to a function

33 ビュー (過去 30 日間)
Mohamed Abdalmoaty
Mohamed Abdalmoaty 2012 年 1 月 26 日
Hello,
I wonder if there is a way to pass not only the value of a variable, but also it's name to a function.
For example, if I have four variables of any type, say a = 1; b = 2; c =3; d =2;
and I have a random function that takes variable number of arguments, for example: randfun
If I used the command out = randfun(a,b,d) for example, the values and types of a, b, d will be stored in the varargin in the workspace.
Is there any way to also know the name (in char type) of the the arguments?
Thank you

採用された回答

Andrew Newell
Andrew Newell 2012 年 1 月 27 日
You can use inputname inside the function to find the names of the variables.
  2 件のコメント
Mohamed Abdalmoaty
Mohamed Abdalmoaty 2012 年 1 月 27 日
Thank you Andrew.
owr
owr 2012 年 1 月 27 日
Didnt know about that one - thanks Andrew!

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

その他の回答 (1 件)

owr
owr 2012 年 1 月 27 日
One solution might be to pass all your input arguments as fields in one structure.
For example, define your input arguments like this:
inputargs.a = 1
inputargs.b = 2
Pass the structure as a single input to your function:
out = randfun(inputargs)
Then within the body of the function "randfun" you can get access to both the variable names and values like this:
>> varnames = fieldnames(inputargs)
varnames =
'a'
'b'
Get access to the name of the first input:
>> varnames{1}
ans =
a
Get access to its value:
>> inputargs.(varnames{1})
ans =
1
Also check out the "inputparser" class in base MATLAB if your version is new enough

カテゴリ

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