ternary operator in matlab

2019-01-18 02:04发布

问题:

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
 false
end

回答1:

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.



回答2:

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.



回答3:

You can do

var = 5 > 4;

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



回答4:

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.



回答5:

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 ...



回答6:

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



回答7:

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!