I'm trying to write a generalised logging function for all the input parameters passed to a function in MATLAB. Is it possible to easily pass all the input parameters to another function without individually naming the parameters? In the logging function, I can of course use inputname(i)
in a for loop to get the parameter names. I would prefer not to have to perform this logic in the main function. So, is there a way to do something like LogParams(allInputParams)
?
views:
167answers:
1
+5
A:
It sounds like you have a main function, and from that function you want to call a function LogParams
to get a list of the names of the variables passed to the main function. Here's one way you could implement your function LogParams
:
function names = LogParams
names = evalin('caller','arrayfun(@inputname,1:nargin,''UniformOutput'',0)');
end
The output returned from LogParams
will be a cell array containing the names of the variables passed to the function that calls LogParams
. The above solution uses the following functions:
- EVALIN: to evaluate an expression in the workspace of the calling function.
- ARRAYFUN: as an alternative to a for loop.
- NARGIN: to get the number of arguments passed to a function.
- INPUTNAME: to get the name of an input variable.
As an illustration of how LogParams
works, create the following function that calls it:
function main_function(a,b,varargin)
disp(LogParams);
end
and now call it with a number of inputs (assuming the variables x
, y
, and z
are defined in the workspace):
>> main_function(x,y)
'x' 'y'
>> main_function(x,y,z)
'x' 'y' 'z'
>> main_function(x,y,z,z,z,z)
'x' 'y' 'z' 'z' 'z' 'z'
gnovice
2010-01-11 20:56:52
Very neat ! .......... (dots to pad to 15 characters)
High Performance Mark
2010-01-12 06:44:38
Thanks. That helps.
Chinmay Kanchi
2010-01-12 14:58:54
+1 for minimum impact to calling function.
Marc
2010-01-13 15:19:06