简体   繁体   English

在MATLAB中包装带有可变参数的方法

[英]Wrap a method with variable arguments in MATLAB

I need to wrap a method with variable arguments. 我需要用可变参数包装一个方法。 For example: 例如:

function p = plot3ex(varargin)

p1 = varargin{1};
p2 = varargin{2};

x = [p1(1,1) p2(1,1)];
y = [p1(2,1) p2(2,1)];
z = [p1(3,1) p2(3,1)];

extraArgs = varargin(3:end);

p = plot3(x,y,z,extraArgs);

When I call this function in the following manner: 当我以以下方式调用此函数时:

p = plot3ex(p1,p2,'--k','DisplayName','My plot 1');  

I get the following error: 我收到以下错误:

Error using plot3 使用plot3
Not enough input arguments. 没有足够的输入参数。

Basically what I need is a method that receives as input two points and any configuration of plot3 . 基本上,我需要的是一种方法,该方法接收输入的两个点和plot3任何配置作为输入。

varargin and ultimately extraArgs is a cell array of contents. varargin和最终extraArgs是内容的单元格数组。 Unpack the rest of the variables as a comma separated list : 将其余变量解压缩为逗号分隔的列表

p = plot3(x, y, z, extraArgs{:});

Note that the use of curly braces - {} is important. 请注意, 花括号 - {}很重要。 How you are calling plot3 currently resolves to the following equivalent function call: 当前如何调用plot3可以解决以下等效函数调用:

p = plot3(x, y, z, {extraArgs{1}, extraArgs{2}, ..., extraArgs{end});

The fourth input parameter is resolved to be a cell array of contents. 第四个输入参数解析为内容的单元格数组。 This is why you are getting an error because what is expected are pairs of strings / flags and associated values. 这就是为什么出现错误的原因,因为期望的是成对的字符串/标志和关联的值。 How you are doing it currently is not correct. 您目前的做法不正确。 You need to unpack the contents of the cell array, but ensuring that the elements are placed in a comma-separated list. 您需要解压缩单元数组的内容,但要确保将元素放在逗号分隔的列表中。

Doing extraArgs{:} is equivalent to doing extraArgs{1}, extraArgs{2}, ..., extraArgs{end} , which is what you would put into the function manually if you were to call plot3 . 进行extraArgs{:}等效于进行extraArgs{1}, extraArgs{2}, ..., extraArgs{end} ,如果要调用plot3手动将其放入函数中。 You are replacing manually specifying the rest of the input parameters by accessing each element in the cell array and splitting up the elements into a comma separated list. 您将通过访问单元格数组中的每个元素并将这些元素拆分为逗号分隔的列表来手动替换其余输入参数。

Therefore, doing extraArgs{:} instead resolves to the following equivalent function call: 因此,执行extraArgs{:}会解析为以下等效函数调用:

p = plot3(x, y, z, extraArgs{1}, extraArgs{2}, ..., extraArgs{end});

... which is what is expected. ...这是预期的。


Example run 运行示例

p1 = [0 0 0].';
p2 = [1 1 1].';
p = plot3ex(p1,p2,'--k','DisplayName','My plot 1');

This gives me: 这给了我:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM