Passing both the the variable name and value to a function

33 vues (au cours des 30 derniers jours)
Mohamed Abdalmoaty
Mohamed Abdalmoaty le 26 Jan 2012
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

Réponse acceptée

Andrew Newell
Andrew Newell le 27 Jan 2012
You can use inputname inside the function to find the names of the variables.
  2 commentaires
Mohamed Abdalmoaty
Mohamed Abdalmoaty le 27 Jan 2012
Thank you Andrew.
owr
owr le 27 Jan 2012
Didnt know about that one - thanks Andrew!

Connectez-vous pour commenter.

Plus de réponses (1)

owr
owr le 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

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by