Using inputname and varargin for dynamic variable creation (?)
이전 댓글 표시
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
Jiro Doke
2011년 2월 1일
If you want the variables to be named based on the variables used to call the function, how do you ensure that your code won't break if called with different variable names? I would be curious to know why you want this behavior.
Sean de Wolski
2011년 2월 1일
I agree with Jiro, don't do this, find another way. What if they input a variable names 'size' or 'length' or some other function that you call within your function?
Bad idea all around.
Jan
2011년 2월 1일
If you need to access strings, use strings and do not mask them as names of variables.
Adam Attarian
2011년 2월 1일
채택된 답변
추가 답변 (1개)
Jiro Doke
2011년 2월 1일
0 개 추천
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.
카테고리
도움말 센터 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!