Pedro77
Pedro77

Reputation: 5294

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
Not enough input arguments.

Basically what I need is a method that receives as input two points and any configuration of plot3.

Upvotes: 1

Views: 72

Answers (1)

rayryeng
rayryeng

Reputation: 104545

varargin and ultimately extraArgs is a cell array of contents. 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:

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. 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:

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:

enter image description here

Upvotes: 4

Related Questions