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
What you refer to is a ternary operator, in C-like notation, ?:. The expression
tern = bool ? T : F
returns T
if bool
evaluates to true, F
otherwise. MATLAB has no ternary operator, however it can be implemented in different ways as an inline expression.
Arrays
% cell array version (any type)
tern = {F,T}{bool+1} % only Octave
tern = subsref({F,T}, struct('type', '{}', 'subs', {{bool+1}}))
% vector array version (numeric types only)
tern = [F,T](bool+1) % only Octave
tern = subsref([F,T], struct('type', '()', 'subs', {{bool+1}}))
Note that T
and F
have been swapped, and that different brackets are used. The vector array version is a specialization for numeric types. MATLAB does not allow direct indexation of fresh arrays, hence the use of subsref
.
tern
, both T
and F
are evaluated.Logical operators and eval
( bool && eval('tern=T') ) || eval('tern=F')
Note that the logical operators are short-circuited.
T
or F
, is evaluated.tern
. eval
is not efficient but required.Basic arithmetic
tern = bool*T + !bool*F
T
or F
are NaN
or Inf
. Both, T
and F
, are evaluated.Maximum
tern = max(T,F) % bool = T>F
Note that this solution fits the particular requirements of the initial question with max(C,0)
.
T
or F
are NaN
. Both, T
and F
, are evaluated. Use is strongly limited.