Filter löschen
Filter löschen

Passing both the the variable name and value to a function

33 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Andrew Newell
Andrew Newell am 27 Jan. 2012
You can use inputname inside the function to find the names of the variables.

Weitere Antworten (1)

owr
owr am 27 Jan. 2012
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

Kategorien

Mehr zu Argument Definitions finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by