Functional IIF function

Another implementation of the "inline if" function, it one takes function handles instead of values.
273 Downloads
Updated 24 May 2013

View License

This function implements the ternary "cond ? then : else" operator. I operates on scalars, matrices and cell arrays.

Instead of precalculated values, it takes function handles which are only applied when the condition is true or false, respectively.

The help text follows:

%iif Implements the ternary ?: operator
% out = iif (@condition, @thenF, elseF@, in[, out])
% out = iif (condition, @thenF, elseF@, in[, out])
%
% The result is equivalent to
% condition(in) ? thenF(in) : elseF(in)
% if condition is a function and
% condition ? thenF(in) : elseF(in)
% else, for each element of the IN argument.
%
% The optional argument OUT serves as a template, if the output type is
% different from the input type, e.g. for mapping arrays to cells and vice
% versa. If it is empty, scalars are assumed for input and output of all
% functions and for the IN argument.
%
% Since using this function may be a bit difficult, here are two examples
% where it is used inside an anonymous function:
%
% (For operation on single values:)
% fun = @(x)(iif(isnumeric(x), ...
% @(y)(y==1), ...
% @(y)(false), ...
% x, []))
%
% (and for operating on a cell array:)
% fun = @(x)(iif(cellfun(@isnumeric, x), ...
% @(y)(num2cell([y{:}]==1)), ...
% @(y)({false}), ...
% x))

Cite As

Daniel Hornung (2024). Functional IIF function (https://www.mathworks.com/matlabcentral/fileexchange/41930-functional-iif-function), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2011a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Function Creation in Help Center and MATLAB Answers
Tags Add Tags
iif

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.0.0.0