将varargs传递给plot()函数 [英] Passing varargs to plot() function
问题描述
我正在为 plot
写一个包装程序,该程序可以自动执行我发现自己经常执行的某些任务.
I am writing a wrapper for plot
that automates some tasks that I find myself doing frequently.
示例代码段可能如下所示
An example code snippet might look like
function myplot(x,y,varargin)
plot(x,y,varargin{:})
xlabel('x axis')
ylabel('y axis')
end
我正在使用Matlab的 varargin
将其他参数传递给 plot
.但是,我发现我可能想在varargin中传递自己的可选参数.例如,我可能想写类似
I'm using Matlab's varargin
to pass additional arguments to plot
. However, I find that I might want to pass my own optional arguments in varargin. For example, I might want to write something like
>> myplot(1:10, 1:10, 'r', 'LineWidth', 2, 'legend', {'Series 1'})
使函数自动在图例中包含图例-也就是说,我希望能够将自己的关键字参数与可以提供给图例的参数相混合.除了没有为我的varargs编写完整的解析器之外,还有什么方法可以在Matlab中简单且可重复使用?
to have the function automatically include a legend in the plot - that is, I want to be able to mix my own keyword arguments with the ones that you can supply to plot. Short of writing a full parser for my varargs, is there a way to do this simply and reusably in Matlab?
我尝试使用 inputParser
对象,但这需要我手动将所有可能的附加参数添加到 plot(以及它的默认值),这似乎并不理想.>
I've tried to use the inputParser
object, but that would require me to manually add every possible additional argument to plot (and a default for it) which doesn't seem ideal.
推荐答案
inputParser
可能仍然是最佳选择.您可以为其他参数构造对象,然后将要传递给 plot
的所有parameterName/parameterValue对合并为 Unmatched
.
inputParser
may still be the best choice. You can construct the object for your additional arguments, and lump all the parameterName/parameterValue pairs that you want to pass to plot
into Unmatched
.
function myplot(x,y,varargin)
parserObj = inputParser;
parserObj.KeepUnmatched = true;
parserObj.AddParamValue('legend',false);
%# and some more of your special arguments
parserObj.parse(varargin);
%# your inputs are in Results
myArguments = parserObj.Results;
%# plot's arguments are unmatched
tmp = [fieldnames(parserObj.Unmatched),struct2cell(parserObj.Unmatched)];
plotArgs = reshape(tmp',[],1)';
plot(x,y,plotArgs{:})
xlabel('x axis')
ylabel('y axis')
if myArguments.legend
%# add your legend
end
end
这篇关于将varargs传递给plot()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!