将varargs传递给plot()函数

Chr*_*lor 4 matlab plot

我正在编写一个包装器来plot自动执行我经常做的一些任务.

示例代码段可能看起来像

function myplot(x,y,varargin)
    plot(x,y,varargin{:})
    xlabel('x axis')
    ylabel('y axis')
end
Run Code Online (Sandbox Code Playgroud)

我正在使用Matlab varargin传递其他参数plot.但是,我发现我可能想在varargin中传递自己的可选参数.例如,我可能想写类似的东西

>> myplot(1:10, 1:10, 'r', 'LineWidth', 2, 'legend', {'Series 1'})
Run Code Online (Sandbox Code Playgroud)

让函数自动在图中包含一个图例 - 也就是说,我希望能够将我自己的关键字参数与您可以提供给图表的参数混合.如果没有为我的varargs编写完整的解析器,有没有办法在Matlab中简单地重复使用?

我试图使用该inputParser对象,但这需要我手动添加每个可能的附加参数到绘图(以及它的默认值),这似乎并不理想.

Jon*_*nas 6

inputParser可能仍然是最好的选择.您可以构造对象为你的其他参数,并把所有要传递给参数名称/对的parameterValue plotUnmatched.

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
Run Code Online (Sandbox Code Playgroud)