Interpreting varargin name-value pairs.
56 次查看(过去 30 天)
显示 更早的评论
I've been writing a lot of functions lately. I like allowing the user to declare options in my functions using name-value pairs, but I have not found a good clean method of interpreting varargin. Here are two methods I tend to use, but both feel a bit clunky:
% Method 1:
for k = 1:length(varargin)
if strcmpi(varargin{k},'fontname')
fontname = varargin{k+1};
varargin{k+1}=[];
varargin{k}=[];
end
end
% Method 2:
nk = 1:length(varargin);
for k = 1:length(varargin)
if strcmpi(varargin{k},'fontsize')
fontsize = varargin{k+1};
nk(k:k+1) = [];
end
end
varargin = varargin(nk);
Is there a better standard procedure for interpreting a list of varargin arguments?
采纳的回答
Sean de Wolski
2014-5-1
8 个评论
Cedric
2014-5-2
编辑:Cedric
2014-5-2
Hi Chad, almost there, look at the KeepUnmatched and Unmatched properties of the parser. You might also be interested in functions fieldnames and struct2cell if you want to build a comma separated list for passing unmatched param/values further.
更多回答(3 个)
Kevin Schroeder
2021-7-20
If it is of any value to others, I have always used a switch case nested in a for loop.
function myFunction(varargin)
for setting = 1:2:nargin
switch varargin{setting}
case 'SettingName1'
value = varargin{setting + 1}
[]; %do stuff with value
case 'SettingName2'
value = varargin{setting + 1}
[]; %do stuff with value
case 'SettingName3'
value = varargin{setting + 1}
[]; %do stuff with value
otherwise
[];
end
end
end
Functionally it should be similar to the nested if statements, but it looks much cleaner.
0 个评论
Justin
2014-5-1
I'm always a fan of cellfun.
inputExist = find(cellfun(@(x) strcmpi(x, 'fontname') , varargin));
if inputExist
fontsize = varargin{inputExist+1};
end
I have used this or something similar before. You can wrap this in a for loop that goes through your expected inputs and instead of assigning them directly to fontsize you could assign it to a structure like:
inputs.(currentName) = varargin{inputExist+1};
Let me know if that makes sense.
1 个评论
Cedric
2014-5-2
编辑:Cedric
2014-5-2
STRCMPI does work on cell arrays, so there is no need to use CELLFUN. Yet, it is likely not to be suited here, because Chad would have to test for all possible parameter names for both the function and the internal function. Using the parser and its Unmachted property is more flexible for this reason.
Alexander
2016-7-17
Dont use inputParser if you need to codegen - it is not supported in R2016a.
1 个评论
Sean de Wolski
2016-7-19
With codegen, you won't be using variable number of inputs since everything needs to be defined.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!