outselect.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. function varargout = outselect(index,sub_idx,func,varargin)
  2. %OUTSELECT Select output arguments of a function.
  3. % OUTSELECT(I,FUNCTION,P1,P2,...) returns one or more of the outputs,
  4. % as selected by the integer(s) in vector I, resulting from the
  5. % function call FUNCTION(P1,P2,...). FUNCTION can be a handle or
  6. % anonymous function.
  7. %
  8. % OUTSELECT(I,FUNCTION) creates a callable form of FUNCTION that always
  9. % returns outputs of the original as specified by I.
  10. %
  11. % Examples:
  12. %
  13. % >> str = 'deacb'; [s,idx] = sort(str)
  14. % s =
  15. % abcde
  16. % idx =
  17. % 3 5 4 1 2
  18. %
  19. % >> [idx,s] = outselect([2 1],@sort,str)
  20. % idx =
  21. % 3 5 4 1 2
  22. % s =
  23. % abcde
  24. %
  25. % >> argmin = outselect(2,@min);
  26. % >> argmin(str)
  27. %
  28. % ans =
  29. % 3
  30. %
  31. % See also FUNCTION_HANDLE.
  32. %
  33. % Copyright 2005 by Tobin Driscoll.
  34. % Revision: 24 June 2005.
  35. if isempty(varargin) % return the callable nested function
  36. varargout{1} = @do_it;
  37. else % apply the nested function once
  38. [varargout{1:nargout}] = do_it(varargin{:});
  39. end
  40. function varargout = do_it(varargin)
  41. [allout{1:max(index)}] = func(varargin{:});
  42. varargout = allout(index);
  43. if sub_idx > 0
  44. varargout = {varargout{1}(sub_idx)};
  45. end
  46. end
  47. end