Skip to content

Instantly share code, notes, and snippets.

@kyamagu
Last active December 28, 2015 03:58
Show Gist options
  • Save kyamagu/7438492 to your computer and use it in GitHub Desktop.
Save kyamagu/7438492 to your computer and use it in GitHub Desktop.
Get a specified output arguments by index.
function varargout = getOutputArguments(index, function_handle, varargin)
%GETOUTPUTARGUMENTS Get specified output arguments by index.
%
% [argument1, argument2, ...] = getOutputArguments(index, function_handle)
%
% Example
% -------
%
% Getting the second output argument of min().
%
% min_index = getOutputArguments(2, @min, values);
%
% Getting the output arguments of sort() in different order.
%
% [order, sorted_values] = getOutputArguments([2,1], @sort, values, 'descend');
%
% See also varargout
number_of_outputs = nargout(function_handle);
assert(number_of_outputs < 0 || number_of_outputs <= max(index), ...
'The function does not return %d output arguments.', max(index));
assert(nargout <= numel(index));
varargout = cell(1, max(index));
[varargout{:}] = feval(function_handle, varargin{:});
varargout = varargout(index);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment