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

后端 未结 10 1280
滥情空心
滥情空心 2020-12-01 11:06

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

10条回答
  •  粉色の甜心
    2020-12-01 11:23

    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.

    • Pros: Works for any type and any value. Can be used inline.
    • Cons: Before returning the result to 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.

    • Pros: Works for any type and any value. Only one, T or F, is evaluated.
    • Cons: Works only in Octave. Can't be used inline, but through the variable tern. eval is not efficient but required.

    Basic arithmetic

    tern = bool*T + !bool*F
    
    • Pros: Can be used inline.
    • Cons: Works only for numeric types, and might fail when 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).

    • Pros: Can be used inline.
    • Cons: Works only for numeric types, and might fail when T or F are NaN. Both, T and F, are evaluated. Use is strongly limited.

提交回复
热议问题