Passing both the the variable name and value to a function

33 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Andrew Newell
Andrew Newell el 27 de En. de 2012
You can use inputname inside the function to find the names of the variables.
  2 comentarios
owr
owr el 27 de En. de 2012
Didnt know about that one - thanks Andrew!

Iniciar sesión para comentar.

Más respuestas (1)

owr
owr el 27 de En. de 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

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by