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
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
You can do
which will set var to true. Just substitute what ever you need for 5 > 4.
I use this style frequently:
it's compact enough to not require a helper function
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:
It's not as simple as ternary operator, but still better than writing it in 5 lines of code.
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.Hmm... no one has mentioned this
somewhere in the docs it is written the `end' is coming to one so this will be more future proof
Usage :
If your in the need of inline cases see Mathworks ...
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 bothtrue_expr
andfalse_expr
, and ifcond
happens not to be either 0 or 1 (note:false
behaves like 0;true
behaves like 1) you'll get crazy results.