Using inputname and varargin for dynamic variable creation (?)

10 次查看(过去 30 天)
Despite my best programming habits, and in an effort to make my code more modular, I use a couple of places varargin.
Of course, the inputs can vary between each use and I check the names of the variables using inputname() and then load from a .mat file any variables that were not passed in but are needed for the code to run.
But now, I need to use the variables that were passed in that are currently lying in varargin{} -- and I need those variable names to be named with what is in inputname{:}...e.g inputname{1}=varargin{1}. I think I could do this with an eval(), but I know that is frowned upon.
I know that [var1, var2, var3]=varargin{:} would work, but the names i need the variables to be called are in inputnams(), and I can't think of how to get this to work.
Is there a good way to get the contents of varargin{} out and into named variables that then lay in the stack?
Thanks!
  4 个评论
Jan
Jan 2011-2-1
If you need to access strings, use strings and do not mask them as names of variables.
Adam Attarian
Adam Attarian 2011-2-1
With no inputs, the code runs a nominal case with parameters (there are five) that are loaded from a .mat file.
My intended behavior is for the code to be able to run with user input'd parameters (any combination of the five), and then the code to load the ones that were not specified. Since I don't know which parameters will be input, I need a way to check, and the best I can come up with is based on the name of the variable.

请先登录,再进行评论。

采纳的回答

Jiro Doke
Jiro Doke 2011-2-1
A couple of options that I can think of:
1. Use assignin. But as you may know, assignin would only allow you to assign to the caller or base workspace. So you can create a function like below, and then call it
assign(inputname(1), varargin{1}).
function assign(varName, varVal)
assignin('caller', varName, varVal);
end
2. Use a structure:
for id = 1:nargin
myVar.(inputname(id)) = varargin{id};
end
And change your code so that it uses myVar instead of individual variables.

更多回答(1 个)

Jiro Doke
Jiro Doke 2011-2-1
According to the OP's comment, it seems that inputParser may be another option. With that, you can specify optional arguments.
For cases where you can have n number of optional arguments (in no particular order), I like to use param-value pairs. I found that to be the most robust. inputParser will also deal with param-value pair input arguments.

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by