MATLAB: How to extract a variable name using varargin
guivarargin
Hello,
I am using varargin in a GUI to allow the user to enter in as many inputs as required, and then plot the input data on a figure. I would like to convert the input argumets into a string that I can use for a legend and/or a title on the figure. I cannot figure out how to extract the variable names using varargin. Is there a way to do this?
Thank You, -Eric
Best Answer
inputname() can still be used when you have varargin.
function blip(a, b, varargin)
for K = 1 : nargin
fprintf('input #%d came from variable "%s"\n', K, inputname(K) );
The simplest solution is that whenever you call your function handle, add this at the end:
fun(...,varargin{:})
For example:
fun_at_x1 = fun(xi(1),varargin{:});
fun_at_x2 = fun(xi(2),varargin{:});
And then call your main function with the extra required parameters that your function requires:
F = @(x, Q) x^3 + Q;
[...] = root_finder(F,[-1,-2],1e-5,50,7)
% ^ include function parameters here.
This solution does not require that your function has a fixed number of parameters: simply define your function handle with whatever input arguments you need, pass the required values as extra input arguments to your main function, and varargin does the rest for you!
Explanation: varargin is simple to understand: it simply collects any trailing input arguments into one cell array named varargin. You can access that cell array just like you would any other cell array:
Best Answer