ternary operator in matlab
Solution 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.
Solution 2
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 ...
Solution 3
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.
Solution 4
You can do
var = 5 > 4;
which will set var to true. Just substitute what ever you need for 5 > 4.
Solution 5
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.
Comments
-
Gün Karagöz almost 2 years
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
-
glglgl over 9 yearsIt should be possible to create a function which takes a condition and two function handles. Then you have the wanted shortcut behaviour.
-
Karl almost 9 yearsNa, you can use (a > b) as a factor and then add another product with the opposite statement :
var = (a < 0) * (-a) + (a >= 0) * (a)
-
Naveen about 8 yearsIf we need to use the ternary operator inside disp or fprintf?
-
BlackDog over 7 yearsElegant but works only for numerical expressions, I tried it with strings and it returned them as an ASCII values array
-
Eric about 7 yearsThis also does not work if
true_expr
orfalse_expr
areinf
-
Juergen S. over 5 yearsNote: a and b are both evaluated. This may be a difference to if ... else ... end.
-
hyiltiz about 4 yearsHoever simple, if/switch/loop statements aren't supported in lambda/anonymous function definitions in Matlab.
-
tommsch almost 4 yearsFor which Matlab version is this? I have R2018a and the assignment var=true_val does not work. Matlab reports a syntax error.
-
Jiří about 2 yearsbeware that this does not work if you need lazy evaluation, e.g.
b
always evaluates regardless ofcond
(might seem obvious, but you probably just think abstract: 'Ah ternary operator here we go' and use it as normal, things might break for you)...