matlabvbaternary-operatorconditional-operatoriif

Is there a Matlab conditional IF operator that can be placed INLINE like VBA's IIF


In VBA I can do the following:

A = B + IIF(C>0, C, 0)

so that if C>0 I get A=B+C and C<=0 I get A=B

Is there an operator or function that will let me do these conditionals inline in MATLAB code?


Solution

  • There is no ternary operator in Matlab. You can, of course, write a function that would do it. For example, the following function works as iif with n-d input for the condition, and with numbers and cells for the outcomes a and b:

    function out = iif(cond,a,b)
    %IIF implements a ternary operator
    
    % pre-assign out
    out = repmat(b,size(cond));
    
    out(cond) = a;
    

    For a more advanced solution, there's a way to create an inline function that can even do elseif, as outlined in this blog post about anonymous function shenanigans:

    iif  = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
    

    You use this function as

    iif(condition_1,value_1,...,true,value_final)
    

    where you replace the dots with any number of additional condition/value pairs.

    The way this works is that it picks among the values the first one whose condition is true. 2*find(),1,'first') provides the index into the value arguments.