ternary operator in matlab

后端 未结 9 1805
后悔当初
后悔当初 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:53

    You can do

    var = 5 > 4;
    

    which will set var to true. Just substitute what ever you need for 5 > 4.

    0 讨论(0)
  • 2020-12-08 20:00

    Hmm... no one has mentioned this

    fi = @(varargin)varargin{end-varargin{1}}
    

    somewhere in the docs it is written the `end' is coming to one so this will be more future proof

    fi = @(varargin)varargin{length(varargin)-varargin{1}}
    

    Usage :

    fi(input('Do you like Matlab ? '),'yes','no')
    >> no
    

    If your in the need of inline cases see Mathworks ...

    0 讨论(0)
  • 2020-12-08 20:00

    I use this style frequently:

    cond = what < ever;
    
    n = getfield([23,42], {1+(what < ever)}) % for any 1x1-data
    s = cell2mat(getfield({'no','yes'}, {1+(what < ever)})) % for nonuniform
    

    it's compact enough to not require a helper function

    0 讨论(0)
提交回复
热议问题