Passing both the the variable name and value to a function

조회 수: 33 (최근 30일)
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 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