feval extensions for working with multiple output arguments

Allows any number of output arguments to be returned from a function in any order and optionally gather to a cell array.
Updated 22 Jan 2020

View License

A common question for MATLAB users is how to get only arguments beyond the first from an output argument list. For example, to simplify the syntax:

[~,ind] = max(A);

to remove the unused argument.

This question becomes more than a matter of convenience when anonymous functions come into play. For instance, how could one write an anonymous function to return the difference of the elements of a vector immediately preceding and following the maximum from the maximum itself?
I.E. f([3 5 4]) == [-2 -1]

The functions in this submission assist with this task by allowing manipulation of the count, order, and format of multiple output arguments.

fevali(iout, fn, ...) - this function re-orders and/or downselects the output argument list

For example, instead of:
[mv,iv] = max(A);
one can do
[iv,mv] = fevali([2 1], @max, A);
or simply
iv = fevali(2, @max, A);

fevalic(iout, fn, ...) - this function not only re-orders the output argument list, but returns all output arguments as a single cell output rather than in varargout list. This enables access to all outputs within an anonymous function.

For example:
c = fevalic(c[2 1], @max, A);
%c{1} contains index of max and c{2} contains the max itself

This can be used to write the earlier requested anonymous function:
prepostmaxdiff = @(x) feval(...
@(x,c) x([c{2}-1 c{2}+1]) - c{1}, ...
x, fevalic(1:2,@max,x) ...
% the first feval evaluates the indexing and difference expression
% the fevalic call returns both outputs of max in a cell array for use in the feval
% c{1} has the max and c{2} has the index of max

fevalnc(nout, fn, ...) - This function is simply a shortcut of fevalic(1:nout, ...).

This submission is similar to https://www.mathworks.com/matlabcentral/fileexchange/53552-fevaln-feval-with-control-of-the-order-of-the-outputs, but adds additional capability to return arguments as a cell array.

Developed and tested on 2019b, but should work back to much earlier versions (as long as argument list expansion is supported).

Cite As

Benjamin Davis (2024). feval extensions for working with multiple output arguments (https://www.mathworks.com/matlabcentral/fileexchange/73992-feval-extensions-for-working-with-multiple-output-arguments), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2019b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Logical in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!


Version Published Release Notes

Removed redundant license file


Updated description


Uploaded missing files