ternary operator in matlab

后端 未结 9 1804
后悔当初
后悔当初 2020-12-08 19:07

is there a way of typing for if like:

var = (cond) ? true : false;

or do we have to use this format?

if (cond)
 true
else
          


        
相关标签:
9条回答
  • 2020-12-08 19:37

    MATLAB doesn't have conditional expressions, but in some situations you can get a similar effect by saying, e.g., var = cond*true_expr + (1-cond)*false_expr. Unlike C's conditional expression, this will of course always evaluate both true_expr and false_expr, and if cond happens not to be either 0 or 1 (note: false behaves like 0; true behaves like 1) you'll get crazy results.

    0 讨论(0)
  • 2020-12-08 19:44

    If you only need true or false, you can do what MatlabSorter suggests. In case you want a real tertiary operator (i.e. a = b ? c : d), there is none in MATLAB. However, using the file supplied here, you can get close.

    0 讨论(0)
  • 2020-12-08 19:46

    MatLab doesn't have a ternary operator, or any other syntactic sugar for one-line if-statements. But if your if-statement is really simple, you could just write it in one line anyway:

    if (cond); casetrue(); else; casefalse(); end
    

    It's not as simple as ternary operator, but still better than writing it in 5 lines of code.

    0 讨论(0)
  • 2020-12-08 19:47

    @Leonid Beschastny is correct about the inlining the if-else-end statement, but If one must, then with any assignment value that can be evaluated as boolean, one can the shortcut boolean operators || and &&:

    (cond) && ((var=true_val)||1) || (var=false_val);
    

    Rules:

    1. shortcut boolean ops || and && must be used, NOT | or &
    2. will work with boolean, numeric and char assignments
    3. will NOT work with cell array or function handles
    4. the assignments must be wrapped in parenthesis.
    5. (var=true_val) must be followed by ||1 in case true_val == false
    6. true and false assignments may be to different variables (i.e. (var1=true_val) while (var2=false_val))
    7. true_val and false_val can be different types provided each then can be evaluated as boolean

    Alternatively one can do this:

    cond && (func1(..)||1) || func2(...);
    

    provided func1 and func2 return a boolean testable value including nothing at all (but no cell arrays!):

    0 讨论(0)
  • 2020-12-08 19:49

    Replace

    c = (x ? a : b)
    

    by

    c = subsref({b; a}, substruct('{}', {x + 1}))
    

    x should be a boolean value or 1 or 0.
    true or 1 will select a
    false or 0 will select b
    This should work with all what cells can contain and can also be used in an intricate formular!

    0 讨论(0)
  • 2020-12-08 19:49

    Quick and elegant. I would simply write tern( a>b, a, b) Downside is you have to copy paste everywhere, or have and extra file in the directory

    function b = tern(cond, a, b)
        if cond
            b=a;
        end
    end
    
    0 讨论(0)
提交回复
热议问题