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

How about simply using the fact that MATLAB automatically converts variable types when required by the operation? E.g., logical to double.

If your variables are scalar double, your code, I believe, can be replaced by

a = b + (c > 0) * c;

In this case, the operator (c > 0) values 1 (logical type) whenever c > 0 and values to 0 otherwise.


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.


There is no built-in solution for this, but you can write an IIF yourself.

function result=iif(cond, t, f)
%IIF - Conditional function that returns T or F, depending of condition COND
%
%  Detailed 
%     Conditional matrix or scalar double function that returns a matrix
%     of same size than COND, with T or F depending of COND boolean evaluation
%     if T or/and F has the same dimensions than COND, it uses the corresponding 
%     element in the assignment
%     if COND is scalar, returns T or F in according with COND evaluation, 
%     even if T or F is matrices like char array.
%
%  Syntax
%    Result = iif(COND, T, F)
%           COND - Matrix or scalar condition
%           T  - expression if COND is true
%           F  - expression if COND is false
%           Result - Matrix or scalar of same dimensions than COND, containing
%                    T if COND element is true or F if COND element is false.
%
if isscalar(cond) 
   if cond 
       result = t;
   else
       result = f;
   end
else
  result = (cond).*t + (~cond).*f;
end  
end