Reputation: 507
I have a function with a variable number of arguments and outputs, and I want it to exit at a certain point if there is an additional argument:
function [out, varargout] = myfunction(a,varargin)
% do stuff
out = 1;
if nargin > 1
return
end
% do extra stuff if there is no additional argument
varargout{1} = 'optional output';
end
I get the error
Output argument "varargout" not assigned during call to "C:\...\myfunction"
How can I solve this?
Upvotes: 3
Views: 3610
Reputation: 14939
How about something like this?
function varargout = my_function(a,varargin)
% do stuff
varargout{1} = 1;
if nargin > 1
if nargout > 1
varargout(2:nargout) = {[]};
end
return
end
% do extra stuff if there is no additional argument
varargout{2} = 'optional output';
end
Test:
[a b] = my_function(2)
a =
1
b =
optional output
[a b] = my_function(2,3)
a =
1
b =
[]
The problem is, you can't call a function with more outputs than it creates. Therefore, calling you original function a = my_function(2,3)
would work fine, while [a b] = my_function(2,3)
will cause an error.
Thus you have (at least) two alternatives:
Make sure the number of output and input variables match every time you execute the function.
Do as I did above.
Upvotes: 3