Logging function parameters in MATLAB
logging, matlab
Solution
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'
Problem
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)`?