[英]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. ...这是预期的。
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.